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 mod layer;
26pub use action::Actions;
27pub use config::Configure;
28
29/// Zenoh's own framing on the data path: a two-byte little-endian length
30/// before every batch, which the driver strips before the medium and re-adds
31/// after (`docs/architecture.md` §4.1). Stated here because a batch of N
32/// bytes puts N - 2 on the medium, and every document that names a
33/// `max_batch_size` has to add it back — the contract's `Capabilities` does.
34pub const LENGTH_PREFIX: usize = 2;
35
36/// The smallest `batch_size` that carries a Zenoh session: 80 bytes.
37///
38/// Zenoh's establishment messages are never fragmented, and the largest is
39/// 78 bytes (`docs/measurements/small-mtu-and-latency.md`, M1), so a medium
40/// whose SDU is below `80 - LENGTH_PREFIX` cannot establish a transport at
41/// any setting. The driver refuses such a configuration where it becomes a
42/// device (#157); a `fragment` layer above the medium is what lifts a
43/// smaller frame over the floor (#162).
44pub const ESTABLISHMENT_FLOOR: u16 = 80;
45
46/// One service data unit: exactly what the medium carries in one transmission.
47///
48/// The driver has already stripped Zenoh's two-byte length prefix by the time an
49/// SDU reaches a backend, and re-adds it on the way back
50/// (`docs/architecture.md` §4.1). Contents are never inspected.
51pub type Sdu = Vec<u8>;
52
53/// A remote endpoint reachable over the medium.
54///
55/// Opaque to the driver and to Zenoh alike. It is a name from configuration —
56/// `"peer-b"`, `"auv-03"`, an IMEI — and per invariant I5 it is an *addressing*
57/// identifier, never a proof of identity.
58#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub struct EndpointId(String);
60
61impl EndpointId {
62 /// Wrap a configured endpoint name.
63 pub fn new(name: impl Into<String>) -> Self {
64 Self(name.into())
65 }
66
67 /// The configured name, for logging and for keying medium-side tables.
68 pub fn as_str(&self) -> &str {
69 &self.0
70 }
71}
72
73impl fmt::Display for EndpointId {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.write_str(&self.0)
76 }
77}
78
79/// The driver's view of one QoS lane.
80///
81/// Under decision D1 a lane is a socket, and its properties come from the
82/// locator metadata Zenoh was configured with (`?rel=1;prio=0-2`) — resolved
83/// once, at startup, into this. A backend schedules lanes; it is never told what
84/// a Zenoh priority is, which is what keeps [`Sdu`] traffic and Zenoh semantics
85/// on opposite sides of this crate boundary.
86#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub struct LaneKey {
88 /// Which remote this lane reaches.
89 pub endpoint: EndpointId,
90 /// Whether this lane promises ordered, loss-free delivery.
91 ///
92 /// Per invariant I2 this is a claim about the *medium*, not a request. A
93 /// backend that cannot honour it must not be configured behind a lane that
94 /// asserts it: Zenoh will not notice the lie, because `verify_sn` accepts a
95 /// forward sequence gap silently — the failure mode is lost data, not a
96 /// fault.
97 pub reliable: bool,
98 /// Scheduling rank; lower is more urgent.
99 ///
100 /// Derived at configuration time from the lane's declared priority range.
101 /// Rank 0 sorts first. The numbering happens to mirror Zenoh's, where
102 /// `Control` is 0, but nothing here depends on that.
103 pub rank: u8,
104}
105
106impl fmt::Display for LaneKey {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 write!(
109 f,
110 "{}/{}#{}",
111 self.endpoint,
112 if self.reliable { "rel" } else { "be" },
113 self.rank
114 )
115 }
116}
117
118/// Whether the medium can transmit and receive simultaneously.
119///
120/// Only the two variants that change behaviour exist. The withdrawn ICD series
121/// carried five, three of which had no consequence anywhere in the
122/// specification; new variants are added here when something acts on them.
123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
125#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
126// Deliberately *not* `#[non_exhaustive]` (#97): a new duplex mode changes what
127// every scheduler and simulator must do, so it should break their builds, and
128// the contract's own `Duplex` maps this one variant for variant.
129pub enum Duplex {
130 /// Transmit and receive are independent.
131 #[default]
132 Full,
133 /// Transmitting blocks receiving and vice versa, as on a shared RF channel.
134 Half,
135}
136
137/// Whether a medium retransmits an SDU it failed to deliver.
138///
139/// This models the modem's *own* link-layer ARQ, which many packet radios and
140/// every store-and-forward satellite service provide. Invariant I2 and
141/// architecture §9 draw the line here: using the modem's ARQ is exactly right,
142/// and inventing one above the modem is what the architecture forbids. A
143/// backend declares what is in front of it (§4.13), and the simulator models
144/// the same three cases, which is why the type is the seam's and not the
145/// simulator's: [`Capabilities::arq`] and a simulated profile's `arq` are one
146/// fact.
147///
148/// It is not free. Every attempt occupies the channel for another airtime, so a
149/// link with ARQ and 5% loss carries measurably more than one without — which
150/// is the whole reason to model it rather than assume it.
151///
152/// Deliberately *not* `#[non_exhaustive]`, for [`Duplex`]'s reason: a fourth
153/// kind of ARQ changes what every reliability claim means, and should break
154/// every match that reasons about it.
155#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
156#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
157#[cfg_attr(
158 feature = "serde",
159 serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)
160)]
161pub enum Arq {
162 /// No retransmission. What a bare packet radio does.
163 #[default]
164 None,
165 /// Retry a fixed number of times, then give up.
166 ///
167 /// Residual loss is `loss^(attempts+1)` — small, but not zero, which is why
168 /// this may not claim reliable delivery.
169 Bounded { attempts: u32 },
170 /// Retry until delivered.
171 ///
172 /// Delivery is guaranteed and latency is not. This is the only ARQ setting
173 /// that may back a lane declaring `rel=1`.
174 Unbounded,
175}
176
177impl Arq {
178 /// The probability an SDU is still lost after this ARQ has finished trying.
179 ///
180 /// Stated rather than implied, so a profile's honesty is checkable and a
181 /// write-up can quote a number.
182 #[must_use]
183 pub fn residual_loss(self, loss: f64) -> f64 {
184 match self {
185 Arq::None => loss,
186 Arq::Bounded { attempts } => loss.powi(attempts as i32 + 1),
187 Arq::Unbounded => 0.0,
188 }
189 }
190
191 /// Whether a medium using this ARQ can honestly claim reliable delivery.
192 #[must_use]
193 pub fn guarantees_delivery(self) -> bool {
194 matches!(self, Arq::Unbounded)
195 }
196}
197
198impl fmt::Display for Arq {
199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200 match self {
201 Arq::None => f.write_str("none"),
202 Arq::Bounded { attempts } => write!(f, "bounded({attempts})"),
203 Arq::Unbounded => f.write_str("unbounded"),
204 }
205 }
206}
207
208/// How a medium's firmware splits an SDU into air frames (#159).
209///
210/// Many radio modules accept a payload larger than their air frame and
211/// fragment it themselves. To the driver that is a medium with a larger SDU;
212/// what the seam needs is the honesty: an SDU of *s* bytes over frames of
213/// *f* is ⌈s/f⌉ frames, each paying its own preamble, and the SDU survives
214/// only if every frame does. A module that fragments without per-frame ARQ
215/// cannot be reliable over a lossy air (I2), and the plane shows the
216/// frames-per-SDU an operator can watch.
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218#[non_exhaustive]
219pub struct Framing {
220 /// Bytes per air frame.
221 pub frame: u16,
222 /// What retransmits a lost *frame*, as the module states it.
223 pub arq: Arq,
224}
225
226impl Framing {
227 /// Frames of `frame` bytes, with `arq` per frame.
228 #[must_use]
229 pub fn new(frame: u16, arq: Arq) -> Self {
230 Self { frame, arq }
231 }
232
233 /// How many frames an SDU of `sdu_len` bytes takes: ⌈s/f⌉, at least one.
234 #[must_use]
235 pub fn frames_for(&self, sdu_len: u16) -> u16 {
236 if self.frame == 0 {
237 return 1;
238 }
239 sdu_len.div_ceil(self.frame).max(1)
240 }
241
242 /// The probability an SDU of `sdu_len` bytes arrives whole over an air
243 /// losing `loss` of its frames: `(1 − residual)^frames`.
244 #[must_use]
245 pub fn survival(&self, loss: f64, sdu_len: u16) -> f64 {
246 (1.0 - self.arq.residual_loss(loss)).powi(i32::from(self.frames_for(sdu_len)))
247 }
248}
249
250/// What a medium can do, as the medium itself would describe it.
251///
252/// Transmit and receive limits are separate because real media are asymmetric:
253/// Iridium SBD carries 340 bytes up and 270 down. Collapsing them to their
254/// minimum — as the withdrawn design did — silently wasted 21% of every paid
255/// uplink message (`docs/architecture.md` §4.9).
256///
257/// `#[non_exhaustive]` since 0.3: a capability a layer or a module adds (the
258/// ARQ, the firmware framing) must not break every implementor's literal.
259/// Build one with [`Capabilities::new`] and the setters.
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261#[non_exhaustive]
262pub struct Capabilities {
263 /// Largest SDU the medium will transmit, in bytes.
264 ///
265 /// `u16` because Zenoh's own `BatchSize` is `u16`, so a larger value could
266 /// never be filled.
267 pub tx_max_sdu: u16,
268 /// Largest SDU the medium will deliver, in bytes.
269 ///
270 /// **A promise this backend makes, and the driver checks it** (#75). An
271 /// arrival larger than this counts `rx_oversize_total` and is logged as a
272 /// contract violation; it is still delivered, because the batch is Zenoh's
273 /// to judge and discarding it here would be the driver deciding a question
274 /// I1 gives to Zenoh.
275 ///
276 /// It is **not** what stops a peer sending too much, and the distinction
277 /// matters on an asymmetric bearer. `batch_size` is node-global and Zenoh
278 /// negotiates the minimum of the two ends, so a pair configured
279 /// inconsistently produces a *small* effective batch — 21% of a paid
280 /// uplink slot wasted on SBD — never an oversized arrival. What an
281 /// operator does with this number is size the *far* node's `batch_size`,
282 /// which is why `Driver::start` logs it as `peer_max_batch_size` (#82).
283 pub rx_max_sdu: u16,
284 /// Whether transmit and receive contend.
285 pub duplex: Duplex,
286 /// Whether the medium delivers in order and without loss.
287 ///
288 /// Per invariant I2 this must be the truth about the hardware, not an
289 /// aspiration. A lane may only assert [`LaneKey::reliable`] over a medium
290 /// that reports `true` here.
291 pub reliable: bool,
292 /// What retransmits a lost SDU, as the module states it (§4.13). The
293 /// claim `reliable` rests on, made explicit: only [`Arq::Unbounded`]
294 /// guarantees delivery.
295 pub arq: Arq,
296 /// How the firmware splits an SDU into air frames, where it does (#159).
297 /// `None` is one SDU, one frame.
298 pub framing: Option<Framing>,
299}
300
301impl Capabilities {
302 /// The four facts every medium states; `arq` defaults to none and
303 /// `framing` to one frame per SDU, which the setters change.
304 #[must_use]
305 pub fn new(tx_max_sdu: u16, rx_max_sdu: u16, duplex: Duplex, reliable: bool) -> Self {
306 Self {
307 tx_max_sdu,
308 rx_max_sdu,
309 duplex,
310 reliable,
311 arq: Arq::None,
312 framing: None,
313 }
314 }
315
316 /// With the module's declared ARQ.
317 #[must_use]
318 pub fn arq(mut self, arq: Arq) -> Self {
319 self.arq = arq;
320 self
321 }
322
323 /// With the module's declared firmware framing.
324 #[must_use]
325 pub fn framing(mut self, framing: Framing) -> Self {
326 self.framing = Some(framing);
327 self
328 }
329}
330
331/// Counters a medium exposes for telemetry.
332///
333/// Deliberately minimal: these are the quantities the driver can assert on in a
334/// test. Radio-specific figures such as RSSI belong on the management plane
335/// (`docs/architecture.md` §4.6), not in the data-path interface.
336///
337/// `#[non_exhaustive]` since 0.3; built with [`Metrics::new`] and the
338/// setters, or `Default`.
339#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
340#[non_exhaustive]
341pub struct Metrics {
342 /// SDUs handed to the medium and accepted.
343 pub tx_sdus: u64,
344 /// Bytes across those SDUs.
345 pub tx_bytes: u64,
346 /// SDUs delivered by the medium.
347 pub rx_sdus: u64,
348 /// Bytes across those SDUs.
349 pub rx_bytes: u64,
350 /// SDUs the medium accepted and then lost, where it can tell.
351 ///
352 /// A medium that cannot distinguish loss from delivery leaves this at zero;
353 /// per the architecture's telemetry rule, absence means unknown and must not
354 /// be read as none.
355 pub dropped: u64,
356}
357
358impl Metrics {
359 /// Every counter at zero.
360 #[must_use]
361 pub fn new() -> Self {
362 Self::default()
363 }
364
365 /// SDUs handed to the medium and accepted.
366 #[must_use]
367 pub fn tx_sdus(mut self, n: u64) -> Self {
368 self.tx_sdus = n;
369 self
370 }
371
372 /// Bytes across the transmitted SDUs.
373 #[must_use]
374 pub fn tx_bytes(mut self, n: u64) -> Self {
375 self.tx_bytes = n;
376 self
377 }
378
379 /// SDUs delivered by the medium.
380 #[must_use]
381 pub fn rx_sdus(mut self, n: u64) -> Self {
382 self.rx_sdus = n;
383 self
384 }
385
386 /// Bytes across the delivered SDUs.
387 #[must_use]
388 pub fn rx_bytes(mut self, n: u64) -> Self {
389 self.rx_bytes = n;
390 self
391 }
392
393 /// SDUs accepted and then lost, where the medium can tell.
394 #[must_use]
395 pub fn dropped(mut self, n: u64) -> Self {
396 self.dropped = n;
397 self
398 }
399}
400
401/// What a device, or a layer above it, guarantees about the bytes it carries
402/// (invariant I6): properties, never a boolean.
403///
404/// "AES enabled" states nothing about mode, key management, peer
405/// authentication, anti-replay or scope, which is why this type has no
406/// `encrypted` field and cannot have one. A device that provides nothing says
407/// `None` from [`Device::security`], and the management plane publishes
408/// exactly that. A layer that seals SDUs (#158) reports what it provides and
409/// only that; a radio that encrypts below the driver reports its own. Every
410/// property here is hop-by-hop: it ends at the neighbour's Zenoh, and a
411/// router that applies key-expression ACLs sees plaintext.
412#[derive(Clone, Debug, PartialEq, Eq)]
413#[non_exhaustive]
414pub struct SecurityProperties {
415 /// Who provides it: `"zenoh-modem aead"`, a radio's own name.
416 pub provider: String,
417 /// How far the guarantee reaches.
418 pub scope: Scope,
419 /// What is guaranteed, each one named.
420 pub guarantees: Vec<Guarantee>,
421 /// The principal the far side was authenticated as, where one was. A key
422 /// shared by more than two nodes proves only "holds the key", and even a
423 /// pairwise key binds a key, not an identity (I5): `None` for both.
424 pub principal: Option<String>,
425}
426
427impl SecurityProperties {
428 /// A provider guaranteeing nothing yet; add guarantees with
429 /// [`guarantee`](Self::guarantee).
430 #[must_use]
431 pub fn new(provider: impl Into<String>, scope: Scope) -> Self {
432 Self {
433 provider: provider.into(),
434 scope,
435 guarantees: Vec::new(),
436 principal: None,
437 }
438 }
439
440 /// One more guarantee, kept unique.
441 #[must_use]
442 pub fn guarantee(mut self, g: Guarantee) -> Self {
443 if !self.guarantees.contains(&g) {
444 self.guarantees.push(g);
445 }
446 self
447 }
448
449 /// The authenticated principal, where there is one.
450 #[must_use]
451 pub fn principal(mut self, p: impl Into<String>) -> Self {
452 self.principal = Some(p.into());
453 self
454 }
455}
456
457/// How far a security property reaches.
458#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
459#[non_exhaustive]
460pub enum Scope {
461 /// One hop: from this node's driver to its neighbour's.
462 Hop,
463}
464
465impl Scope {
466 /// The wire spelling.
467 #[must_use]
468 pub const fn as_str(self) -> &'static str {
469 match self {
470 Self::Hop => "hop",
471 }
472 }
473}
474
475impl fmt::Display for Scope {
476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 f.write_str(self.as_str())
478 }
479}
480
481/// One thing a provider guarantees, in the words `docs/design/link-security.md`
482/// uses.
483#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
484#[non_exhaustive]
485pub enum Guarantee {
486 /// Nobody on the channel reads the payload.
487 Confidentiality,
488 /// A changed or forged SDU is refused.
489 Integrity,
490 /// A repeated SDU is refused.
491 AntiReplay,
492 /// The peer was authenticated when the transport was established, and
493 /// nothing after that.
494 PeerAuthenticationAtEstablishment,
495}
496
497impl Guarantee {
498 /// The wire spelling, kebab-case.
499 #[must_use]
500 pub const fn as_str(self) -> &'static str {
501 match self {
502 Self::Confidentiality => "confidentiality",
503 Self::Integrity => "integrity",
504 Self::AntiReplay => "anti-replay",
505 Self::PeerAuthenticationAtEstablishment => "peer-authentication-at-establishment",
506 }
507 }
508}
509
510impl fmt::Display for Guarantee {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.write_str(self.as_str())
513 }
514}
515
516/// One named counter a device or a layer keeps beyond the fixed vocabulary
517/// of [`Metrics`] and [`Report`] (#157): a layer's refusals, a module's
518/// frames.
519///
520/// The management plane publishes a counter only under a subject the
521/// registry declares for its `scope` and `name`, gated per scope, so a
522/// counter nobody declared is visible in a log and nowhere else, and the
523/// registry never lies about what is served.
524#[derive(Clone, Debug, PartialEq, Eq)]
525#[non_exhaustive]
526pub struct Counter {
527 /// Who keeps it: a layer's kind (`"aead"`), or `"air"` for a medium's
528 /// frames.
529 pub scope: String,
530 /// What it counts: `auth_failures_total`.
531 pub name: String,
532 /// Its value now.
533 pub value: u64,
534}
535
536impl Counter {
537 /// A counter by scope and name.
538 #[must_use]
539 pub fn new(scope: impl Into<String>, name: impl Into<String>, value: u64) -> Self {
540 Self {
541 scope: scope.into(),
542 name: name.into(),
543 value,
544 }
545 }
546}
547
548/// What a device says about itself, as far as it knows.
549///
550/// `Capabilities` is what the medium *can* carry and is read once; `Metrics` is
551/// what the driver counted and is what a test asserts on. This is the third
552/// thing, and the one that fell off the edge: what the hardware knows about its
553/// own condition. `modem-device` named the gap years before it had a shape —
554/// "radio-specific figures such as RSSI belong on the management plane" — and
555/// then never built the other side of it (#49).
556///
557/// **Every field is `Option`, and that is load-bearing twice over.** A device
558/// that cannot answer says `None` rather than zero, because a zeroed counter is
559/// a claim and absence is not. And several implementors in this workspace are
560/// decorators wrapping another `Medium`; a decorator that forgets to forward
561/// this method inherits the default, whose every field is `None` — the same
562/// answer as "I do not know", rather than a confident wrong number belonging to
563/// the medium underneath.
564///
565/// `#[non_exhaustive]` because #49 lists eleven quantities and hardware will
566/// suggest twenty more. As fields on one struct behind one defaulted method,
567/// adding `signal.rssi_dbm` later touches the backend that fills it and the
568/// publisher that reads it — as methods, each would be an eight-implementor
569/// event for ever.
570#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
571#[non_exhaustive]
572pub struct Report {
573 /// How long ago this snapshot was taken.
574 ///
575 /// [`Device::report`] is sync, so a backend cannot do I/O in it and
576 /// must answer from a cache. A cache with no age is a lie the moment the
577 /// modem stops answering, which is exactly when an operator is reading it —
578 /// so the age rides along, and a report older than a consumer's tolerance is
579 /// published as absent rather than as current.
580 pub age_ms: Option<u64>,
581
582 /// Cumulative channel occupancy, in milliseconds.
583 ///
584 /// What the medium has actually spent on the air. On a service billed in
585 /// airtime this is the bill; `lease-tuning-in-a-cell.md` is the measurement
586 /// that made the distinction between this and a message count matter.
587 pub time_on_air_ms: Option<u64>,
588
589 /// Transmissions made only because an earlier attempt was lost.
590 ///
591 /// The medium's own ARQ, which `rf-arq-requirement.md` makes a hardware
592 /// selection requirement. Counted by every simulator in the tree today and
593 /// reachable through none of them.
594 pub retransmits: Option<u64>,
595
596 /// Slot bytes paid for and not used.
597 ///
598 /// A per-message service charges for the whole slot; M2 measured 9.4%
599 /// utilisation at the defaults. This is the same figure from the medium's
600 /// side, for a deployment rather than for a measurement.
601 pub bytes_wasted: Option<u64>,
602
603 /// Frames the medium received and could not accept: FIFO overrun,
604 /// collision, CRC or header failure.
605 ///
606 /// **Distinct from [`Metrics::dropped`]**, which is accepted-then-lost on
607 /// *transmit*. #49 describes these as conflated; they are not — no shipped
608 /// medium puts receive-side errors into `dropped` — but they are counted
609 /// (`sim.rs`'s `lost_attempts`, `cell.rs`'s `collisions` and `overruns`) and
610 /// have had no way out of the crate at all.
611 pub rx_errors: Option<u64>,
612
613 /// Whether the medium may transmit now, and how long until it may.
614 pub duty_cycle: Option<DutyCycle>,
615
616 /// Received signal strength, on the device's own 0–5 scale.
617 ///
618 /// **Bars, not dBm, and the distinction is the point.** An Iridium ISU
619 /// answers `AT+CSQF` with an integer 0–5 and has no dBm to give; an
620 /// SX1262 reads a dBm out of a packet-status register and has no bars.
621 /// A field spelled `rssi_dbm` would force one of them to invent a number,
622 /// which is the failure `Report`'s all-`Option` shape exists to
623 /// avoid — a device says what it knows and stays quiet about the rest. A
624 /// dBm field arrives with the backend that measures one (#49, #76).
625 pub signal_bars: Option<u8>,
626
627 // --- The IP-bearer vocabulary (#123). Names carry no unit suffix: the
628 // registry's `unit` is where a unit lives, and a name-and-field pair is
629 // two places to drift. Fixed-point, because this type is `Copy + Eq`:
630 // milli-units cover RSRQ's and SNR's half-dB steps exactly.
631 /// Received signal strength, milli-dBm (ModemManager `Modem.Signal`,
632 /// an SX1262's packet status).
633 pub rssi: Option<i32>,
634 /// Reference signal received power, milli-dBm (LTE, NR).
635 pub rsrp: Option<i32>,
636 /// Reference signal received quality, milli-dB.
637 pub rsrq: Option<i32>,
638 /// Signal-to-noise ratio, milli-dB.
639 pub snr: Option<i32>,
640 /// Error rate, milli-percent.
641 pub error_rate: Option<i32>,
642 /// Current receive data rate, bit/s (DLEP, RFC 8175 §13 — session level;
643 /// per-destination metrics are not device-level and are not here).
644 pub rx_rate: Option<u64>,
645 /// Current transmit data rate, bit/s.
646 pub tx_rate: Option<u64>,
647 /// Maximum receive data rate, bit/s.
648 pub rx_max_rate: Option<u64>,
649 /// Maximum transmit data rate, bit/s.
650 pub tx_max_rate: Option<u64>,
651 /// Latency, microseconds.
652 pub latency: Option<u64>,
653 /// Resources available on the link, milli-percent.
654 pub resources: Option<i32>,
655 /// Relative receive link quality, milli-percent.
656 pub rx_quality: Option<i32>,
657 /// Relative transmit link quality, milli-percent.
658 pub tx_quality: Option<i32>,
659 /// Network registration, for a bearer that registers with one.
660 pub registration: Option<Registration>,
661 /// The access technology the bearer is on.
662 pub access_technology: Option<AccessTechnology>,
663}
664
665impl Report {
666 /// An empty report — the same thing [`Device::report`]'s default
667 /// returns, and the starting point for a backend that fills some of it.
668 ///
669 /// The setters below take and return `self` so a backend names only what it
670 /// knows: `Report::new().retransmits(n).rx_errors(m)`. That shape is
671 /// what makes `#[non_exhaustive]` free rather than annoying — this type is
672 /// implemented from *outside* this crate, so a struct literal would make
673 /// every new field a breaking change, which is exactly the churn #49's
674 /// eleven-and-counting quantities would cause.
675 #[must_use]
676 pub fn new() -> Self {
677 Self::default()
678 }
679
680 /// How old this snapshot is. See [`Report::age_ms`].
681 #[must_use]
682 pub fn age_ms(mut self, ms: u64) -> Self {
683 self.age_ms = Some(ms);
684 self
685 }
686
687 /// Cumulative channel occupancy.
688 #[must_use]
689 pub fn time_on_air_ms(mut self, ms: u64) -> Self {
690 self.time_on_air_ms = Some(ms);
691 self
692 }
693
694 /// Transmissions made only because an earlier attempt was lost.
695 #[must_use]
696 pub fn retransmits(mut self, n: u64) -> Self {
697 self.retransmits = Some(n);
698 self
699 }
700
701 /// Slot bytes paid for and not used.
702 #[must_use]
703 pub fn bytes_wasted(mut self, n: u64) -> Self {
704 self.bytes_wasted = Some(n);
705 self
706 }
707
708 /// Frames received and not accepted.
709 #[must_use]
710 pub fn rx_errors(mut self, n: u64) -> Self {
711 self.rx_errors = Some(n);
712 self
713 }
714
715 /// Whether the medium may transmit now.
716 #[must_use]
717 pub fn duty_cycle(mut self, duty: DutyCycle) -> Self {
718 self.duty_cycle = Some(duty);
719 self
720 }
721
722 /// Signal strength on the device's own 0–5 scale.
723 #[must_use]
724 pub fn signal_bars(mut self, bars: u8) -> Self {
725 self.signal_bars = Some(bars);
726 self
727 }
728
729 /// Received signal strength, milli-dBm.
730 #[must_use]
731 pub fn rssi(mut self, milli_dbm: i32) -> Self {
732 self.rssi = Some(milli_dbm);
733 self
734 }
735
736 /// Reference signal received power, milli-dBm.
737 #[must_use]
738 pub fn rsrp(mut self, milli_dbm: i32) -> Self {
739 self.rsrp = Some(milli_dbm);
740 self
741 }
742
743 /// Reference signal received quality, milli-dB.
744 #[must_use]
745 pub fn rsrq(mut self, milli_db: i32) -> Self {
746 self.rsrq = Some(milli_db);
747 self
748 }
749
750 /// Signal-to-noise ratio, milli-dB.
751 #[must_use]
752 pub fn snr(mut self, milli_db: i32) -> Self {
753 self.snr = Some(milli_db);
754 self
755 }
756
757 /// Error rate, milli-percent.
758 #[must_use]
759 pub fn error_rate(mut self, milli_percent: i32) -> Self {
760 self.error_rate = Some(milli_percent);
761 self
762 }
763
764 /// Current receive data rate, bit/s.
765 #[must_use]
766 pub fn rx_rate(mut self, bps: u64) -> Self {
767 self.rx_rate = Some(bps);
768 self
769 }
770
771 /// Current transmit data rate, bit/s.
772 #[must_use]
773 pub fn tx_rate(mut self, bps: u64) -> Self {
774 self.tx_rate = Some(bps);
775 self
776 }
777
778 /// Maximum receive data rate, bit/s.
779 #[must_use]
780 pub fn rx_max_rate(mut self, bps: u64) -> Self {
781 self.rx_max_rate = Some(bps);
782 self
783 }
784
785 /// Maximum transmit data rate, bit/s.
786 #[must_use]
787 pub fn tx_max_rate(mut self, bps: u64) -> Self {
788 self.tx_max_rate = Some(bps);
789 self
790 }
791
792 /// Latency, microseconds.
793 #[must_use]
794 pub fn latency(mut self, us: u64) -> Self {
795 self.latency = Some(us);
796 self
797 }
798
799 /// Resources available on the link, milli-percent.
800 #[must_use]
801 pub fn resources(mut self, milli_percent: i32) -> Self {
802 self.resources = Some(milli_percent);
803 self
804 }
805
806 /// Relative receive link quality, milli-percent.
807 #[must_use]
808 pub fn rx_quality(mut self, milli_percent: i32) -> Self {
809 self.rx_quality = Some(milli_percent);
810 self
811 }
812
813 /// Relative transmit link quality, milli-percent.
814 #[must_use]
815 pub fn tx_quality(mut self, milli_percent: i32) -> Self {
816 self.tx_quality = Some(milli_percent);
817 self
818 }
819
820 /// Network registration.
821 #[must_use]
822 pub fn registration(mut self, r: Registration) -> Self {
823 self.registration = Some(r);
824 self
825 }
826
827 /// The access technology the bearer is on.
828 #[must_use]
829 pub fn access_technology(mut self, t: AccessTechnology) -> Self {
830 self.access_technology = Some(t);
831 self
832 }
833}
834
835/// Where a bearer stands with its network (ModemManager's 3GPP registration
836/// states; #123). A device that registers with nothing — a point-to-point
837/// radio — reports none.
838#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
839#[non_exhaustive]
840pub enum Registration {
841 /// Not registered, not searching.
842 Idle,
843 /// Registered on the home network.
844 Home,
845 /// Searching for a network.
846 Searching,
847 /// Registration denied.
848 Denied,
849 /// Registered, roaming.
850 Roaming,
851 /// The device cannot say.
852 Unknown,
853}
854
855impl Registration {
856 /// The wire spelling.
857 #[must_use]
858 pub const fn as_str(self) -> &'static str {
859 match self {
860 Self::Idle => "idle",
861 Self::Home => "home",
862 Self::Searching => "searching",
863 Self::Denied => "denied",
864 Self::Roaming => "roaming",
865 Self::Unknown => "unknown",
866 }
867 }
868}
869
870impl fmt::Display for Registration {
871 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872 f.write_str(self.as_str())
873 }
874}
875
876/// The access technology a bearer is on (#123). Closed and
877/// `#[non_exhaustive]`: a value is added when a device produces it, and a
878/// reader that sees one it does not know treats it as text.
879#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
880#[non_exhaustive]
881pub enum AccessTechnology {
882 Gsm,
883 Gprs,
884 Edge,
885 Umts,
886 Hspa,
887 Lte,
888 /// LTE-M (Cat-M1), ModemManager's `lte-cat-m`.
889 LteM,
890 /// NB-IoT, ModemManager's `lte-nb-iot`.
891 NbIot,
892 Nr5g,
893 /// Iridium's own air interface — an SBD terminal.
894 Iridium,
895}
896
897impl AccessTechnology {
898 /// The wire spelling: ModemManager's, lowercase.
899 #[must_use]
900 pub const fn as_str(self) -> &'static str {
901 match self {
902 Self::Gsm => "gsm",
903 Self::Gprs => "gprs",
904 Self::Edge => "edge",
905 Self::Umts => "umts",
906 Self::Hspa => "hspa",
907 Self::Lte => "lte",
908 Self::LteM => "lte-cat-m",
909 Self::NbIot => "lte-nb-iot",
910 Self::Nr5g => "5gnr",
911 Self::Iridium => "iridium",
912 }
913 }
914}
915
916impl fmt::Display for AccessTechnology {
917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
918 f.write_str(self.as_str())
919 }
920}
921
922/// Why a medium is not transmitting, when the answer is "not yet".
923///
924/// The case #49 calls sharpest, and the reason it is in v1 rather than deferred
925/// with the rest: a compliant EU868 backend must **block** in `send` for up to
926/// ~99 s, and an operator watching `queue_depth` climb cannot tell
927/// "duty-cycle limited" from "radio dead". `SimMedium::slide_to_contact` already
928/// blocks for exactly this reason and `ContactWindow::wait_at` already computes
929/// the number, so this is a producer that exists rather than a keyspace row
930/// waiting for hardware.
931#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
932#[non_exhaustive]
933pub struct DutyCycle {
934 /// Whether the medium would take an SDU right now.
935 pub available: bool,
936 /// Milliseconds until it would, when it would not.
937 ///
938 /// Zero while [`available`](Self::available) is false means the medium is
939 /// blocked and does not know for how long, which is a different answer from
940 /// "blocked for 0 ms" and a real state for a device that can say it is busy
941 /// without saying when it will not be.
942 pub next_available_in_ms: u64,
943}
944
945impl DutyCycle {
946 /// The medium would take an SDU now.
947 #[must_use]
948 pub fn ready() -> Self {
949 Self {
950 available: true,
951 next_available_in_ms: 0,
952 }
953 }
954
955 /// The medium would not, and this is how long until it would.
956 ///
957 /// Two named constructors rather than one taking `(bool, u64)`, because the
958 /// two states are what a caller is choosing between and a boolean argument
959 /// at a call site says nothing about which way round it goes.
960 #[must_use]
961 pub fn wait_ms(ms: u64) -> Self {
962 Self {
963 available: false,
964 next_available_in_ms: ms,
965 }
966 }
967}
968
969/// Something the medium wants to say when nobody is calling [`Medium::send`].
970///
971/// The gap #51 names: every `DeviceError` is the return value of a data-path
972/// call, so a radio that loses registration, overheats, or drops off the bus is
973/// silent until the next transmission — which on a store-and-forward link may
974/// be an hour away, and on a dead one is never.
975///
976/// A plain struct rather than a channel, and that is the whole reason this
977/// works. `modem-device` has three dependencies — `async-trait`, `thiserror`,
978/// optional `serde` — and **no tokio**. Putting a `watch::Receiver` or a
979/// `broadcast::Receiver` on the trait would drag a runtime into a crate whose
980/// entire job is to be the seam, to obtain a channel type. An `async fn`
981/// mirroring [`Medium::recv`] needs nothing, is dyn-compatible through the
982/// `async-trait` already here, and has a default whose meaning is exactly
983/// "this medium never says anything".
984#[derive(Clone, Debug, PartialEq, Eq)]
985#[non_exhaustive]
986pub struct DeviceEvent {
987 /// The lane it concerns, if it concerns one.
988 ///
989 /// `None` for a device-wide condition — registration lost, over
990 /// temperature, duty-cycle budget exhausted — which is most of them.
991 pub lane: Option<LaneKey>,
992 /// Whether this is the medium becoming unhappy or becoming happy again.
993 ///
994 /// Edge-triggered by contract. A backend that repeated `Raised` while a
995 /// condition persisted would produce a stream no `rate` declaration could
996 /// honestly cover, and the consumer's job is to publish these, not to
997 /// deduplicate somebody else's.
998 pub edge: Edge,
999 /// The device's own words.
1000 ///
1001 /// Carried verbatim to the management plane, which is the point: until #51
1002 /// a `DeviceError::Device(String)` reached a `warn!` and was discarded, so
1003 /// `+CME ERROR 3` — the one thing that says what is actually wrong — never
1004 /// left the process.
1005 pub detail: String,
1006}
1007
1008impl DeviceEvent {
1009 /// A condition beginning.
1010 #[must_use]
1011 pub fn raised(detail: impl Into<String>) -> Self {
1012 Self {
1013 lane: None,
1014 edge: Edge::Raised,
1015 detail: detail.into(),
1016 }
1017 }
1018
1019 /// A condition ending.
1020 #[must_use]
1021 pub fn cleared(detail: impl Into<String>) -> Self {
1022 Self {
1023 lane: None,
1024 edge: Edge::Cleared,
1025 detail: detail.into(),
1026 }
1027 }
1028
1029 /// Attribute this event to one lane.
1030 #[must_use]
1031 pub fn on_lane(mut self, lane: LaneKey) -> Self {
1032 self.lane = Some(lane);
1033 self
1034 }
1035}
1036
1037/// Which way a condition just went.
1038#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1039#[non_exhaustive]
1040pub enum Edge {
1041 /// It started.
1042 Raised,
1043 /// It stopped.
1044 Cleared,
1045}
1046
1047/// Why a medium refused or failed an SDU.
1048///
1049/// `#[non_exhaustive]`: both consumers on the data path already match with a
1050/// catch-all (`sched.rs`'s retry arm, `lanes.rs`'s receive loop), so this costs
1051/// nothing today and leaves room for the variants a real device will need. The
1052/// alternative is discovering later that adding one is a breaking change to a
1053/// crate whose whole job is to be implemented from outside.
1054#[derive(Debug, thiserror::Error)]
1055#[non_exhaustive]
1056pub enum DeviceError {
1057 /// The SDU is larger than the medium can carry.
1058 ///
1059 /// Invariant I4: the driver never splits a batch to make it fit. An SDU that
1060 /// does not fit is a configuration error — Zenoh's `batch_size` was set
1061 /// above what this medium can carry — and it is reported, loudly, as one.
1062 #[error(
1063 "sdu of {got} bytes exceeds the medium's tx_max_sdu of {max}: \
1064 lower zenoh's batch_size to at most {} (architecture I4, §4.5)", *max as usize + 2
1065 )]
1066 SduTooLarge { got: usize, max: u16 },
1067
1068 /// No such lane is configured on this medium.
1069 #[error("unknown lane {0} (architecture §4.1)")]
1070 UnknownLane(LaneKey),
1071
1072 /// The medium is up but cannot transmit right now, and says so rather than
1073 /// waiting.
1074 ///
1075 /// For hardware whose API refuses instead of blocking — a half-duplex
1076 /// medium mid-reception, on a device that reports rather than queues.
1077 ///
1078 /// **A contact window is still not an instance of this.** A satellite
1079 /// terminal out of coverage *blocks*, because that is what a
1080 /// store-and-forward service does. See
1081 /// `docs/measurements/contact-windows.md`.
1082 ///
1083 /// What returning it costs, exactly: on a **reliable** lane the scheduler
1084 /// holds the batch and offers it again with a backoff, for as long as the
1085 /// medium keeps refusing (#40) — so this trades a stall for a delay, never
1086 /// for lost data, and the stall reaches Zenoh as ordinary backpressure. On
1087 /// a **best-effort** lane the batch is dropped and counted, which is what
1088 /// best-effort means. Either way the refusal appears on
1089 /// `DriverMetrics::tx_failed`.
1090 ///
1091 /// Earlier versions of this note warned that the scheduler dropped the
1092 /// batch on both lane classes. It did, silently, and that was #40.
1093 #[error("medium cannot transmit at present")]
1094 TxUnavailable,
1095
1096 /// The medium is gone: closed, unplugged, or failed.
1097 #[error("medium is closed")]
1098 Closed,
1099
1100 /// Anything hardware-specific, in the backend's own words.
1101 ///
1102 /// Handled exactly as [`DeviceError::TxUnavailable`]: held and retried on
1103 /// a reliable lane, dropped and counted on a best-effort one. Return it
1104 /// for a failure the medium expects to survive — `+CME ERROR`, an SPI
1105 /// timeout, an MO status of "no network". A device that is *gone* should
1106 /// say [`DeviceError::Closed`] instead, which stops the driver rather
1107 /// than retrying into it.
1108 ///
1109 /// The string reaches the management plane verbatim. `sched::transmit`
1110 /// raises a [`DeviceEvent`] carrying it, the driver's event stream carries
1111 /// that, and it is published as `events/modem/device_fault/<ulid>` with the
1112 /// text in `detail` (#51). Write it for an operator, not for a log grep:
1113 /// it is the only place a device speaks in its own words.
1114 #[error("medium error: {0}")]
1115 Device(String),
1116}
1117
1118/// RFC 2863's operational status — the states something here produces.
1119///
1120/// `dormant`, `testing` and `lowerLayerDown` are not declared, deliberately: a
1121/// state is added when a device produces it. Linux's operstate documentation
1122/// defines dormant as "L1 up, but waiting for an external event", and a
1123/// coverage gap is L1 down — so a terminal out of coverage is [`Down`] with
1124/// [`OperStatus::recoverable`] set, never dormant (#121).
1125///
1126/// [`Down`]: OperState::Down
1127#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1128#[non_exhaustive]
1129pub enum OperState {
1130 /// Passing traffic.
1131 Up,
1132 /// Not passing traffic; [`OperStatus::recoverable`] says whether it
1133 /// expects to again without help.
1134 Down,
1135 /// The device node is gone: a serial port unplugged, an interface
1136 /// removed. Distinct from `Down` because no amount of waiting fixes it.
1137 NotPresent,
1138 /// The device has not said, and nothing else can tell. The default.
1139 Unknown,
1140}
1141
1142impl OperState {
1143 /// The wire spelling: RFC 2863's own, so `notPresent` keeps its case.
1144 #[must_use]
1145 pub const fn as_str(self) -> &'static str {
1146 match self {
1147 Self::Up => "up",
1148 Self::Down => "down",
1149 Self::NotPresent => "notPresent",
1150 Self::Unknown => "unknown",
1151 }
1152 }
1153}
1154
1155impl fmt::Display for OperState {
1156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1157 f.write_str(self.as_str())
1158 }
1159}
1160
1161/// RFC 2863's administrative status: what was asked of the device.
1162///
1163/// Exists so that radio silence is expressible and distinguishable from a
1164/// failure — an operator who ordered EMCON reads `admin: down, status: down`
1165/// and knows nothing broke. Ordering it is a hot configuration group (#126).
1166#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1167#[non_exhaustive]
1168pub enum AdminState {
1169 /// Asked to carry traffic.
1170 #[default]
1171 Up,
1172 /// Asked to be silent.
1173 Down,
1174}
1175
1176impl AdminState {
1177 /// The wire spelling.
1178 #[must_use]
1179 pub const fn as_str(self) -> &'static str {
1180 match self {
1181 Self::Up => "up",
1182 Self::Down => "down",
1183 }
1184 }
1185}
1186
1187impl fmt::Display for AdminState {
1188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 f.write_str(self.as_str())
1190 }
1191}
1192
1193/// What a device says about whether it is working (#121).
1194///
1195/// Sync and cached, like [`Report`]: the management plane polls it, and a
1196/// device that needs I/O to answer keeps a snapshot. Every field is a fact
1197/// the device has; a device that has none returns [`OperStatus::unknown`],
1198/// which is the default and is honest. It cannot be derived from
1199/// [`DeviceEvent`], whose detail is free text.
1200#[derive(Clone, Debug, PartialEq, Eq)]
1201#[non_exhaustive]
1202pub struct OperStatus {
1203 /// The operational status.
1204 pub status: OperState,
1205 /// The administrative status.
1206 pub admin: AdminState,
1207 /// Why, in the device's words, when it is not up.
1208 pub reason: Option<String>,
1209 /// Whether the device expects to come back on its own. `false` is the
1210 /// one value that means something — a dead medium — and is what a
1211 /// supervisor reads before deciding to restart (#96). A coverage gap is
1212 /// `true`; so are `up` and `unknown`, because neither is a reason to
1213 /// restart.
1214 pub recoverable: bool,
1215 /// When the status last changed, on the device's clock.
1216 pub since: Option<std::time::SystemTime>,
1217}
1218
1219impl Default for OperStatus {
1220 fn default() -> Self {
1221 Self::unknown()
1222 }
1223}
1224
1225impl OperStatus {
1226 fn with(status: OperState, reason: Option<String>, recoverable: bool) -> Self {
1227 Self {
1228 status,
1229 admin: AdminState::Up,
1230 reason,
1231 recoverable,
1232 since: None,
1233 }
1234 }
1235
1236 /// The device has not said. The default.
1237 #[must_use]
1238 pub fn unknown() -> Self {
1239 Self::with(OperState::Unknown, None, true)
1240 }
1241
1242 /// Passing traffic.
1243 #[must_use]
1244 pub fn up() -> Self {
1245 Self::with(OperState::Up, None, true)
1246 }
1247
1248 /// Not passing traffic, with the reason and whether it expects to again.
1249 #[must_use]
1250 pub fn down(reason: impl Into<String>, recoverable: bool) -> Self {
1251 Self::with(OperState::Down, Some(reason.into()), recoverable)
1252 }
1253
1254 /// The device node is gone.
1255 #[must_use]
1256 pub fn not_present(reason: impl Into<String>) -> Self {
1257 Self::with(OperState::NotPresent, Some(reason.into()), false)
1258 }
1259
1260 /// When this status began, on the device's clock.
1261 #[must_use]
1262 pub fn since(mut self, at: std::time::SystemTime) -> Self {
1263 self.since = Some(at);
1264 self
1265 }
1266
1267 /// With the administrative status.
1268 #[must_use]
1269 pub fn admin(mut self, admin: AdminState) -> Self {
1270 self.admin = admin;
1271 self
1272 }
1273
1274 /// Whether the device is passing traffic.
1275 #[must_use]
1276 pub fn is_up(&self) -> bool {
1277 self.status == OperState::Up
1278 }
1279}
1280
1281/// What a device is, with RFC 8348's field names (#122).
1282///
1283/// Every field optional and the type `#[non_exhaustive]`: a device says what
1284/// it knows, and a field arrives when a device produces it. **Subscriber
1285/// identifiers never appear here** — an IMSI, an ICCID, an MSISDN identifies
1286/// a person's subscription, not equipment (invariant I5). The equipment
1287/// identifier does, because the gateway keys its endpoints by it; it is an
1288/// addressing identifier, never a proof of identity.
1289#[derive(Clone, Debug, Default, PartialEq, Eq)]
1290#[non_exhaustive]
1291pub struct Identity {
1292 /// Who made it.
1293 pub mfg_name: Option<String>,
1294 /// What it is, in the maker's words.
1295 pub model_name: Option<String>,
1296 /// The maker's serial number.
1297 pub serial_num: Option<String>,
1298 /// Hardware revision.
1299 pub hardware_rev: Option<String>,
1300 /// Firmware revision.
1301 pub firmware_rev: Option<String>,
1302 /// Software revision, where it is distinct from the firmware's.
1303 pub software_rev: Option<String>,
1304 /// The bearer's equipment identifier — an IMEI.
1305 pub imei: Option<String>,
1306}
1307
1308impl Identity {
1309 /// A device that knows nothing about itself.
1310 #[must_use]
1311 pub fn unknown() -> Self {
1312 Self::default()
1313 }
1314
1315 /// Whether the device said anything at all.
1316 #[must_use]
1317 pub fn is_empty(&self) -> bool {
1318 *self == Self::default()
1319 }
1320
1321 fn set(mut self, field: fn(&mut Self) -> &mut Option<String>, v: impl Into<String>) -> Self {
1322 *field(&mut self) = Some(v.into());
1323 self
1324 }
1325
1326 /// With the maker's name.
1327 #[must_use]
1328 pub fn mfg_name(self, v: impl Into<String>) -> Self {
1329 self.set(|i| &mut i.mfg_name, v)
1330 }
1331
1332 /// With the model name.
1333 #[must_use]
1334 pub fn model_name(self, v: impl Into<String>) -> Self {
1335 self.set(|i| &mut i.model_name, v)
1336 }
1337
1338 /// With the serial number.
1339 #[must_use]
1340 pub fn serial_num(self, v: impl Into<String>) -> Self {
1341 self.set(|i| &mut i.serial_num, v)
1342 }
1343
1344 /// With the hardware revision.
1345 #[must_use]
1346 pub fn hardware_rev(self, v: impl Into<String>) -> Self {
1347 self.set(|i| &mut i.hardware_rev, v)
1348 }
1349
1350 /// With the firmware revision.
1351 #[must_use]
1352 pub fn firmware_rev(self, v: impl Into<String>) -> Self {
1353 self.set(|i| &mut i.firmware_rev, v)
1354 }
1355
1356 /// With the software revision.
1357 #[must_use]
1358 pub fn software_rev(self, v: impl Into<String>) -> Self {
1359 self.set(|i| &mut i.software_rev, v)
1360 }
1361
1362 /// With the equipment identifier.
1363 #[must_use]
1364 pub fn imei(self, v: impl Into<String>) -> Self {
1365 self.set(|i| &mut i.imei, v)
1366 }
1367}
1368
1369/// A device: anything the driver serves on the management plane.
1370///
1371/// The core and introspection planes of `docs/design/device-planes.md`, and
1372/// nothing about how bytes move — that is [`Medium`] for an SDU device, and
1373/// a netdev's is the kernel's. Every method is defaulted, because a device
1374/// that says nothing about itself is a legitimate device and every simulator
1375/// was one until #49; the split from the old `Backend` (#117) changed no
1376/// behaviour, only which trait a method belongs to.
1377#[async_trait::async_trait]
1378pub trait Device: Send + Sync {
1379 /// What this device says about itself.
1380 ///
1381 /// Defaulted to "nothing", because a medium that knows nothing about its
1382 /// own condition is a legitimate medium and every simulator was one until
1383 /// #49. Sync rather than `async` **on purpose**: the driver calls this from
1384 /// `mgmt/telemetry.rs`'s five-second publish loop, and an `async` signature
1385 /// would invite a backend to put an AT-command round trip there. A device
1386 /// that needs I/O to answer keeps atomics and a cached snapshot, and says
1387 /// how old the snapshot is through [`Report::age_ms`].
1388 ///
1389 /// **Decorators must forward this.** Several implementors in this workspace
1390 /// wrap another `Medium`, and one that inherits the default answers `None` to
1391 /// everything — which reads as "unknown" rather than as a wrong number, but
1392 /// is still a lie about the medium underneath. The conformance kit's
1393 /// [`conformance::medium_decorator_forwards`] is what catches it, and it
1394 /// covers the whole trait rather than this method alone — which is new: the
1395 /// check this comment named for three issues asserted `report` and
1396 /// nothing else, and `close`, `configure_lanes` and `next_event` had gone
1397 /// unforwarded behind the claim (#50, #51, #52).
1398 fn report(&self) -> Report {
1399 Report::default()
1400 }
1401
1402 /// Whether this device is working, as RFC 2863 has it (#121).
1403 ///
1404 /// Sync and cached, for [`report`](Device::report)'s reason. Defaulted to
1405 /// [`OperStatus::unknown`]: a device that cannot tell says so, and the
1406 /// plane publishes that rather than a guess. A medium that has *failed*
1407 /// need not report it here — the driver knows, and overlays `down` with
1408 /// `recoverable: false` on whatever the device says. What a device does
1409 /// know that the driver cannot is the recoverable kind of down: a
1410 /// coverage gap, a closed contact window, a carrier that dropped.
1411 ///
1412 /// **Decorators must forward this**, like everything else here.
1413 fn oper(&self) -> OperStatus {
1414 OperStatus::default()
1415 }
1416
1417 /// What this device is (#122): RFC 8348's fields and the bearer's
1418 /// equipment identifier, as much of it as the device knows.
1419 ///
1420 /// Sync and cached, for [`report`](Device::report)'s reason: a modem
1421 /// reads its model, firmware and IMEI once, at open, and answers from
1422 /// that. Defaulted to [`Identity::unknown`], which is a legitimate
1423 /// answer — the management plane publishes it as a document with only
1424 /// the device's name, and a reader knows the device was asked. The plane
1425 /// polls it and raises `identity_change` when it differs: a terminal
1426 /// swapped, or its firmware updated, under a running driver.
1427 ///
1428 /// **Never a subscriber identifier** (I5). **Decorators must forward
1429 /// this**, like everything else here.
1430 fn identity(&self) -> Identity {
1431 Identity::default()
1432 }
1433
1434 /// Wait for the next thing the medium wants to say.
1435 ///
1436 /// Mirrors [`recv`](Medium::recv) deliberately: a driver drains this in
1437 /// its own task, so a backend may block here for as long as it likes and a
1438 /// medium with nothing to report simply never resolves. The default is
1439 /// exactly that, which is why every medium in this workspace needs no
1440 /// implementation.
1441 ///
1442 /// **Edge-triggered.** One event when a condition starts and one when it
1443 /// stops, not a repeat while it persists — see [`Edge`]. A backend that
1444 /// repeated itself would produce a rate the `events` keyspace cannot
1445 /// honestly declare, and the driver deduplicating on its behalf would be
1446 /// guessing at which repeats meant something.
1447 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1448 std::future::pending().await
1449 }
1450
1451 /// Stop, cleanly.
1452 ///
1453 /// Called once, on the way down, after every lane task has been aborted and
1454 /// before the process exits. The default does nothing, because an
1455 /// in-process medium has nothing to release.
1456 ///
1457 /// **A real device does (#50).** Teardown used to be: `Driver::shutdown`
1458 /// aborts its tasks, the `Arc<dyn Medium>` is dropped, and anything a
1459 /// radio needed to be told happened in `Drop` with no `async` available. A
1460 /// radio left keyed, or a modem left in binary-write mode, is the
1461 /// observable consequence — and neither is visible while a simulator is the
1462 /// only implementor, because a simulator never needs telling.
1463 ///
1464 /// Errors are reported and not propagated: the process is going away, and
1465 /// there is nothing a caller could do differently. Say what failed.
1466 async fn close(&self) -> Result<(), DeviceError> {
1467 Ok(())
1468 }
1469
1470 /// This device's configuration plane, if it has one (#125).
1471 ///
1472 /// `None` is the honest default: a device with nothing to configure
1473 /// declares no resource, and the management plane serves none for it.
1474 fn configuration(&self) -> Option<&dyn Configure> {
1475 None
1476 }
1477
1478 /// The operator actions this device offers (#129): explicit, costed,
1479 /// never scheduled — an operator deciding, once, now. `None` for a
1480 /// device with none. There is no `reset` and there will not be one
1481 /// (architecture §4.11): recovery is a restart, of the device (the
1482 /// driver's own `reopen` action) or of the daemon (#96).
1483 fn actions(&self) -> Option<&dyn Actions> {
1484 None
1485 }
1486
1487 /// What this device guarantees about the bytes it carries (I6), as
1488 /// properties. `None`, the default, is a device that provides nothing,
1489 /// which every medium in this workspace is: the management plane
1490 /// publishes that as `provider: none` with an empty guarantee set, never
1491 /// as `encrypted: false`. A layer that seals SDUs, or a radio that
1492 /// encrypts below the driver, answers with what it provides and only
1493 /// that. **Decorators must forward this**, like everything else here.
1494 fn security(&self) -> Option<SecurityProperties> {
1495 None
1496 }
1497
1498 /// Counters beyond the fixed vocabulary (#157): a layer's refusals, a
1499 /// module's frames. Empty by default. Sync and cached, like
1500 /// [`report`](Device::report); the management plane publishes those the
1501 /// registry declares, gated by scope. **Decorators must forward this.**
1502 fn counters(&self) -> Vec<Counter> {
1503 Vec::new()
1504 }
1505}
1506
1507/// A physical or simulated medium: the SDU data plane of a [`Device`].
1508///
1509/// Implementations own everything below the driver: framing on the air, vendor
1510/// APIs, contact scheduling, radio state. They own nothing above it — no
1511/// routing, no retransmission the hardware does not already provide, and no
1512/// knowledge of what the bytes mean. `Medium: Device`, so an `Arc<dyn Medium>`
1513/// upcasts to `Arc<dyn Device>` and the management plane serves it like any
1514/// other device.
1515#[async_trait::async_trait]
1516pub trait Medium: Device {
1517 /// What this medium can carry. Read once at startup to size lanes.
1518 fn capabilities(&self) -> Capabilities;
1519
1520 /// Transmit one SDU on one lane.
1521 ///
1522 /// Returns once the medium has taken ownership — which is *not* a delivery
1523 /// receipt. Implementations must apply backpressure by not returning, rather
1524 /// than by accepting into an unbounded queue: invariant I3 exists because a
1525 /// hidden backlog between Zenoh's congestion control and the radio defeats
1526 /// the whole design.
1527 async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError>;
1528
1529 /// Wait for the next SDU the medium delivers.
1530 ///
1531 /// Returns the lane it arrived on, so the driver can route it back to the
1532 /// matching socket without inspecting the payload.
1533 async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError>;
1534
1535 /// A snapshot of this medium's counters.
1536 fn metrics(&self) -> Metrics;
1537
1538 /// Tell the medium which lanes this driver will serve.
1539 ///
1540 /// Called once, from `Driver::start`, before anything moves. The default
1541 /// does nothing, because a medium that was given its topology at
1542 /// construction has nothing to learn — which is every medium in this
1543 /// workspace, and was every medium there was when the trait was written.
1544 ///
1545 /// **A real backend needs this and had no way to get it (#52).** `recv`
1546 /// returns a `LaneKey`, and hardware receives bytes with no lane in them:
1547 /// the endpoint can be recovered from on-air framing, but `reliable` and
1548 /// `rank` have to be *synthesised*, and nothing told the backend what
1549 /// combinations exist. Guess wrong and the driver drops the batch on a lane
1550 /// it does not have — silently until #52's first commit, and counted as
1551 /// `rx_unroutable_total` since.
1552 ///
1553 /// The driver is the authority here: these are the lanes it resolved from
1554 /// its own config and will actually serve, not the lanes a config file
1555 /// mentioned. Returning an error refuses startup, which is the right
1556 /// response to a medium that cannot serve what it is being asked for.
1557 async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
1558 let _ = lanes;
1559 Ok(())
1560 }
1561}
1562
1563/// A device whose data plane is the kernel's: a network interface that Zenoh
1564/// reaches over an ordinary TCP link bound to it (#118, #130).
1565///
1566/// Nothing here moves a byte — that is the point. The driver serves such a
1567/// device on the management plane exactly as it serves a [`Medium`], and the
1568/// lanes, the scheduler and the framing never see it: `Netdev: Device`, not
1569/// `Netdev: Medium`. The kernel's view (statistics, the presence epoch) is
1570/// this trait's; what the vendor's control API knows (signal, registration,
1571/// data rates) arrives through [`Device::report`], and an adapter that wraps
1572/// the kernel view with a vendor's must forward both.
1573pub trait Netdev: Device {
1574 /// The interface name, as the kernel spells it: `wwan0`, `ppp0`.
1575 fn interface(&self) -> &str;
1576
1577 /// The interface's counters, as the kernel keeps them (#130): sync and
1578 /// cached, like [`Device::report`]. A counter the kernel does not keep
1579 /// is absent, never zero.
1580 fn statistics(&self) -> NetdevStats {
1581 NetdevStats::default()
1582 }
1583
1584 /// The presence epoch (zenkey RFC 04 §5, v1.39): moves when the
1585 /// interface is re-enumerated (its `ifindex` changed) or a counter is
1586 /// observed to decrease — what a USB modem re-enumerating looks like —
1587 /// and the management plane cycles `device/{device}/alive` when it does,
1588 /// which is the one reset the registry sanctions for the counters under
1589 /// this device. `0` until it moves.
1590 fn epoch(&self) -> u64 {
1591 0
1592 }
1593
1594 /// The neighbours the device's radio reports it can reach (#137): a
1595 /// DLEP radio's destinations. `None`, the default, is a device that has
1596 /// no such notion, which is every netdev that is not a radio with a
1597 /// neighbour table; `Some` of an empty list is one that has the notion
1598 /// and no neighbour now. Sync and cached, like
1599 /// [`statistics`](Netdev::statistics).
1600 ///
1601 /// **Not endpoints** (architecture §4.6): an endpoint is a remote the
1602 /// operator configured lanes toward; a destination is what a radio
1603 /// discovered, and comes and goes on its own.
1604 fn destinations(&self) -> Option<Vec<Destination>> {
1605 None
1606 }
1607}
1608
1609/// One neighbour a netdev's radio can reach (#137), as the radio reports
1610/// it. The metrics are the radio's for the link toward this neighbour, in
1611/// the units [`Report`] uses for the same quantities, and absent where the
1612/// radio gives only session-wide ones.
1613#[derive(Clone, Debug, Default, PartialEq, Eq)]
1614#[non_exhaustive]
1615pub struct Destination {
1616 /// How the radio names it, spelled as a key chunk: for DLEP its MAC
1617 /// address, lowercase hex separated by hyphens.
1618 pub id: String,
1619 /// The addresses the radio says it has.
1620 pub addresses: Vec<std::net::IpAddr>,
1621 /// Current receive data rate toward it, bit/s.
1622 pub rx_rate: Option<u64>,
1623 /// Current transmit data rate, bit/s.
1624 pub tx_rate: Option<u64>,
1625 /// Maximum receive data rate, bit/s.
1626 pub rx_max_rate: Option<u64>,
1627 /// Maximum transmit data rate, bit/s.
1628 pub tx_max_rate: Option<u64>,
1629 /// Latency, microseconds.
1630 pub latency: Option<u64>,
1631 /// Resources available toward it, milli-percent.
1632 pub resources: Option<i32>,
1633 /// Relative receive link quality, milli-percent.
1634 pub rx_quality: Option<i32>,
1635 /// Relative transmit link quality, milli-percent.
1636 pub tx_quality: Option<i32>,
1637}
1638
1639impl Destination {
1640 /// A destination known by `id` and nothing else yet. The fields are
1641 /// public and set directly; this type is `#[non_exhaustive]` so that a
1642 /// new metric is not a breaking change.
1643 #[must_use]
1644 pub fn new(id: impl Into<String>) -> Self {
1645 Self {
1646 id: id.into(),
1647 ..Self::default()
1648 }
1649 }
1650
1651 /// With these addresses.
1652 #[must_use]
1653 pub fn addresses(mut self, addresses: Vec<std::net::IpAddr>) -> Self {
1654 self.addresses = addresses;
1655 self
1656 }
1657}
1658
1659/// A network interface's counters (#130), with RFC 8343's names where Linux
1660/// keeps exactly that counter and nothing else.
1661///
1662/// `in_pkts` and `out_pkts` are **not** RFC 8343's: the RFC splits packets by
1663/// unicast, multicast and broadcast, Linux's `rx_packets` includes multicast,
1664/// and Linux keeps no broadcast counter. They are here because an operator
1665/// asks for them; the registry says what they are.
1666///
1667/// `#[non_exhaustive]` since 0.3; built with [`NetdevStats::new`] and the
1668/// setters, or `Default`.
1669#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1670#[non_exhaustive]
1671pub struct NetdevStats {
1672 /// `rx_bytes` — RFC 8343 `in-octets`.
1673 pub in_octets: Option<u64>,
1674 /// `tx_bytes` — RFC 8343 `out-octets`.
1675 pub out_octets: Option<u64>,
1676 /// `rx_errors` — RFC 8343 `in-errors`.
1677 pub in_errors: Option<u64>,
1678 /// `tx_errors` — RFC 8343 `out-errors`.
1679 pub out_errors: Option<u64>,
1680 /// `rx_dropped` — RFC 8343 `in-discards`.
1681 pub in_discards: Option<u64>,
1682 /// `tx_dropped` — RFC 8343 `out-discards`.
1683 pub out_discards: Option<u64>,
1684 /// `multicast` — RFC 8343 `in-multicast-pkts`.
1685 pub in_multicast_pkts: Option<u64>,
1686 /// `rx_packets` — not RFC 8343: unicast and multicast together.
1687 pub in_pkts: Option<u64>,
1688 /// `tx_packets` — not RFC 8343.
1689 pub out_pkts: Option<u64>,
1690 /// Bytes queued in the interface's queue discipline now, not yet sent
1691 /// (#136). Not a sysfs counter: read over netlink, and only from the
1692 /// kernel's own interface. The queue an operator watches form when a
1693 /// bearer is slower than what is offered to it.
1694 pub qdisc_backlog_bytes: Option<u64>,
1695 /// Packets queued in the queue discipline now (#136).
1696 pub qdisc_backlog_pkts: Option<u64>,
1697}
1698
1699macro_rules! netdev_stat_setters {
1700 ($($name:ident),* $(,)?) => {
1701 impl NetdevStats {
1702 /// Every counter absent.
1703 #[must_use]
1704 pub fn new() -> Self {
1705 Self::default()
1706 }
1707 $(
1708 #[doc = concat!("With `", stringify!($name), "`.")]
1709 #[must_use]
1710 pub fn $name(mut self, n: u64) -> Self {
1711 self.$name = Some(n);
1712 self
1713 }
1714 )*
1715 }
1716 };
1717}
1718
1719netdev_stat_setters!(
1720 in_octets,
1721 out_octets,
1722 in_errors,
1723 out_errors,
1724 in_discards,
1725 out_discards,
1726 in_multicast_pkts,
1727 in_pkts,
1728 out_pkts,
1729 qdisc_backlog_bytes,
1730 qdisc_backlog_pkts,
1731);
1732
1733#[cfg(test)]
1734mod tests {
1735 use super::*;
1736
1737 fn lane(rank: u8, reliable: bool) -> LaneKey {
1738 LaneKey {
1739 endpoint: EndpointId::new("peer-b"),
1740 reliable,
1741 rank,
1742 }
1743 }
1744
1745 #[test]
1746 fn the_operational_states_spell_themselves_as_rfc_2863_does() {
1747 assert_eq!(OperState::Up.as_str(), "up");
1748 assert_eq!(OperState::Down.as_str(), "down");
1749 assert_eq!(OperState::NotPresent.as_str(), "notPresent");
1750 assert_eq!(OperState::Unknown.as_str(), "unknown");
1751 assert_eq!(AdminState::Down.to_string(), "down");
1752 }
1753
1754 #[test]
1755 fn a_device_that_says_nothing_is_unknown_and_not_a_reason_to_restart() {
1756 let s = OperStatus::default();
1757 assert_eq!(s.status, OperState::Unknown);
1758 assert_eq!(s.admin, AdminState::Up);
1759 assert!(s.recoverable, "unknown is not a reason to restart");
1760 assert!(s.reason.is_none());
1761 assert!(!s.is_up());
1762 assert!(!OperStatus::down("dead", false).recoverable);
1763 assert!(OperStatus::down("no coverage", true).recoverable);
1764 assert!(!OperStatus::not_present("port unplugged").recoverable);
1765 assert!(OperStatus::up().is_up());
1766 }
1767
1768 #[test]
1769 fn an_identity_says_only_what_the_device_knows() {
1770 assert!(Identity::unknown().is_empty());
1771 let id = Identity::unknown()
1772 .model_name("IRIDIUM 9603")
1773 .imei("300234060000000");
1774 assert!(!id.is_empty());
1775 assert_eq!(id.model_name.as_deref(), Some("IRIDIUM 9603"));
1776 assert_eq!(id.mfg_name, None, "unasked is absent, not empty");
1777 }
1778
1779 #[test]
1780 fn the_vocabulary_keeps_the_report_copy_and_eq_at_fixed_point() {
1781 // RSRQ and SNR move in half-dB steps; milli-units hold them exactly,
1782 // which is what lets `Report` stay `Copy + Eq` without an `f64`.
1783 let r = Report::new()
1784 .rssi(-97_500)
1785 .rsrq(-10_500)
1786 .snr(12_000)
1787 .rx_rate(1_000_000)
1788 .latency(45_000)
1789 .registration(Registration::Home)
1790 .access_technology(AccessTechnology::Lte);
1791 assert_eq!(r, r, "Eq");
1792 let copy = r;
1793 assert_eq!(copy.rssi, Some(-97_500));
1794 assert_eq!(r.rsrp, None, "unmeasured is absent");
1795 assert_eq!(Registration::Home.as_str(), "home");
1796 assert_eq!(AccessTechnology::Nr5g.as_str(), "5gnr");
1797 }
1798
1799 #[test]
1800 fn a_lane_renders_as_endpoint_reliability_and_rank() {
1801 assert_eq!(lane(0, true).to_string(), "peer-b/rel#0");
1802 assert_eq!(lane(5, false).to_string(), "peer-b/be#5");
1803 }
1804
1805 #[test]
1806 fn lanes_differing_only_in_reliability_are_distinct() {
1807 assert_ne!(lane(0, true), lane(0, false));
1808 }
1809
1810 #[test]
1811 fn capabilities_may_be_asymmetric() {
1812 // The SBD profile: 340 up, 270 down. Nothing here collapses them.
1813 let caps = Capabilities::new(340, 270, Duplex::Full, true).arq(Arq::Unbounded);
1814 assert_ne!(caps.tx_max_sdu, caps.rx_max_sdu);
1815 assert_eq!(caps.framing, None);
1816 }
1817
1818 #[test]
1819 fn framing_counts_frames_and_their_survival() {
1820 let f = Framing::new(64, Arq::None);
1821 assert_eq!(f.frames_for(220), 4);
1822 assert_eq!(f.frames_for(64), 1);
1823 assert_eq!(f.frames_for(0), 1);
1824 let p = f.survival(0.05, 220);
1825 assert!((p - 0.95f64.powi(4)).abs() < 1e-12, "{p}");
1826 assert_eq!(Framing::new(64, Arq::Unbounded).survival(0.05, 220), 1.0);
1827 assert_eq!(Arq::Bounded { attempts: 3 }.to_string(), "bounded(3)");
1828 }
1829
1830 #[test]
1831 fn security_properties_name_what_they_guarantee_and_nothing_else() {
1832 let p = SecurityProperties::new("test", Scope::Hop)
1833 .guarantee(Guarantee::Integrity)
1834 .guarantee(Guarantee::Integrity);
1835 assert_eq!(p.guarantees, vec![Guarantee::Integrity]);
1836 assert_eq!(p.principal, None);
1837 assert_eq!(Guarantee::AntiReplay.as_str(), "anti-replay");
1838 assert_eq!(Scope::Hop.as_str(), "hop");
1839 }
1840
1841 #[test]
1842 fn an_oversized_sdu_names_the_batch_size_that_would_fit() {
1843 // The +2 is Zenoh's length prefix, which lives inside the batch buffer:
1844 // a batch_size of N puts N-2 bytes on the medium.
1845 let e = DeviceError::SduTooLarge { got: 300, max: 218 };
1846 assert_eq!(
1847 e.to_string(),
1848 "sdu of 300 bytes exceeds the medium's tx_max_sdu of 218: \
1849 lower zenoh's batch_size to at most 220 (architecture I4, §4.5)"
1850 );
1851 }
1852}