dvb_ci_runtime/device.rs
1//! The hardware-abstraction boundary: [`CaDevice`].
2//!
3//! EN 50221 runs over the Linux CA device (`/dev/dvb/adapterN/caM`): the
4//! application reads/writes the TPDU link-layer byte stream and issues a few
5//! ioctls (reset, slot info, capabilities). The runtime is written entirely
6//! against this trait so it can be driven by a real device (the `linux`
7//! feature) *or* by an in-memory mock — which is what makes the state machines
8//! testable without hardware, and enables differential testing against an
9//! external reference (feed both the same mock, compare the emitted
10//! write/ioctl sequences).
11
12use std::io;
13
14/// CA-device slot status (subset of the Linux `ca_slot_info` the runtime needs).
15///
16/// The DVB-CA slot reports two independent bits (uapi `linux/dvb/ca.h`
17/// `ca_slot_info.flags`): `CA_CI_MODULE_PRESENT` (a module is physically
18/// inserted) and `CA_CI_MODULE_READY` (that module has completed its own
19/// init and is usable). A module can be present-but-not-ready briefly after
20/// insertion; the runtime's hot-plug edge detection
21/// ([`Notification::HotPlug`](crate::event::Notification::HotPlug) carrying
22/// [`HotPlug::CamPresent`](crate::event::HotPlug::CamPresent)/
23/// [`CamRemoved`](crate::event::HotPlug::CamRemoved)) keys off
24/// `module_present`, since that is the field that toggles on physical
25/// insert/removal.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub struct SlotInfo {
28 /// Slot number.
29 pub num: u8,
30 /// `true` once a module is present and ready (`CA_CI_MODULE_READY`).
31 pub module_ready: bool,
32 /// `true` while a module is physically inserted (`CA_CI_MODULE_PRESENT`),
33 /// regardless of whether it has finished initialising.
34 pub module_present: bool,
35}
36
37/// The link-layer device the EN 50221 runtime drives.
38///
39/// All methods mirror the operations a host performs on the CA file descriptor
40/// per EN 50221. Implementations: [`MockCaDevice`] (in-memory, for tests +
41/// differential harness) and the `linux` `CaDevice` over `/dev/dvb/.../ca`.
42pub trait CaDevice {
43 /// Read one link-layer TPDU frame into `buf`; returns the byte count.
44 /// `Ok(0)` means no data available (non-blocking).
45 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
46
47 /// Write one link-layer TPDU frame.
48 fn write(&mut self, buf: &[u8]) -> io::Result<()>;
49
50 /// Reset the interface / slot (ioctl `CA_RESET`).
51 fn reset(&mut self) -> io::Result<()>;
52
53 /// Query slot status (ioctl `CA_GET_SLOT_INFO`).
54 fn slot_info(&mut self) -> io::Result<SlotInfo>;
55
56 /// Wait up to `timeout` for the device to become readable; `Ok(true)` if
57 /// readable. The runtime's poll loop calls this between reads.
58 fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool>;
59}
60
61/// One recorded device operation, for assertions + differential testing.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum DeviceOp {
64 /// A `write()` of these exact bytes.
65 Write(Vec<u8>),
66 /// A `reset()` ioctl.
67 Reset,
68 /// A `slot_info()` ioctl.
69 SlotInfo,
70}
71
72/// In-memory [`CaDevice`] for tests and the differential harness.
73///
74/// - `inbound` is a scripted queue of frames the "module" (mock CAM) sends up;
75/// each [`read`](CaDevice::read) pops one.
76/// - every host-side operation is appended to `ops` so a test (or a differential
77/// comparison against an external reference) can assert the exact emitted
78/// `write`/ioctl sequence.
79#[derive(Debug, Default)]
80pub struct MockCaDevice {
81 /// Scripted frames the module sends to the host (FIFO).
82 pub inbound: std::collections::VecDeque<Vec<u8>>,
83 /// Recorded host-side operations, in order.
84 pub ops: Vec<DeviceOp>,
85 /// Slot status returned by [`slot_info`](CaDevice::slot_info).
86 pub slot: SlotInfo,
87}
88
89impl MockCaDevice {
90 /// New mock with a ready module in slot 0 and the given inbound script.
91 #[must_use]
92 pub fn new(inbound: impl IntoIterator<Item = Vec<u8>>) -> Self {
93 Self {
94 inbound: inbound.into_iter().collect(),
95 ops: Vec::new(),
96 slot: SlotInfo {
97 num: 0,
98 module_ready: true,
99 module_present: true,
100 },
101 }
102 }
103
104 /// The bytes written by the host so far, concatenated (convenience for
105 /// byte-exact differential comparison against the C reference).
106 #[must_use]
107 pub fn written(&self) -> Vec<u8> {
108 self.ops
109 .iter()
110 .filter_map(|o| match o {
111 DeviceOp::Write(b) => Some(b.clone()),
112 _ => None,
113 })
114 .flatten()
115 .collect()
116 }
117}
118
119impl CaDevice for MockCaDevice {
120 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
121 match self.inbound.pop_front() {
122 Some(frame) => {
123 let n = frame.len().min(buf.len());
124 buf[..n].copy_from_slice(&frame[..n]);
125 Ok(n)
126 }
127 None => Ok(0),
128 }
129 }
130
131 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
132 self.ops.push(DeviceOp::Write(buf.to_vec()));
133 Ok(())
134 }
135
136 fn reset(&mut self) -> io::Result<()> {
137 self.ops.push(DeviceOp::Reset);
138 Ok(())
139 }
140
141 fn slot_info(&mut self) -> io::Result<SlotInfo> {
142 self.ops.push(DeviceOp::SlotInfo);
143 Ok(self.slot)
144 }
145
146 fn poll(&mut self, _timeout: std::time::Duration) -> io::Result<bool> {
147 Ok(!self.inbound.is_empty())
148 }
149}
150
151/// One link-layer event for diagnostics, captured in both directions by
152/// [`RecordingCaDevice`].
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum LinkEvent {
155 /// Host → module: a frame the host wrote.
156 Tx(Vec<u8>),
157 /// Module → host: a frame the host read.
158 Rx(Vec<u8>),
159 /// A `reset()` ioctl.
160 Reset,
161 /// A `slot_info()` ioctl and the status it returned.
162 SlotInfo(SlotInfo),
163}
164
165/// A [`CaDevice`] decorator that records every frame in **both** directions
166/// (plus ioctls) for live-CAM diagnostics. Wrap a real device, run, then dump
167/// the [`log`](Self::log) — or decode it with
168/// [`trace::decode_log`](crate::trace::decode_log) — to get an annotated byte
169/// trace without hand-instrumenting the device:
170///
171/// ```no_run
172/// # use dvb_ci_runtime::{Driver, device::RecordingCaDevice, trace};
173/// # fn real_device() -> dvb_ci_runtime::MockCaDevice { dvb_ci_runtime::MockCaDevice::new([]) }
174/// let mut driver = Driver::new(RecordingCaDevice::new(real_device()));
175/// driver.init().unwrap();
176/// // ... pump ...
177/// println!("{}", trace::decode_log(driver.device().log()));
178/// ```
179#[derive(Debug, Default)]
180pub struct RecordingCaDevice<D> {
181 inner: D,
182 /// The captured link events, in order.
183 pub log: Vec<LinkEvent>,
184 /// Last logged slot status, so repeated identical `slot_info()` polls
185 /// (the driver now samples every [`pump`](crate::Driver::pump) for
186 /// hot-plug edge detection — #726) don't swamp the trace; only a change
187 /// is recorded, same rationale as `poll()` below.
188 last_slot: Option<SlotInfo>,
189}
190
191impl<D: CaDevice> RecordingCaDevice<D> {
192 /// Wrap `inner`, recording all I/O.
193 pub fn new(inner: D) -> Self {
194 Self {
195 inner,
196 log: Vec::new(),
197 last_slot: None,
198 }
199 }
200
201 /// The recorded link events, in order.
202 #[must_use]
203 pub fn log(&self) -> &[LinkEvent] {
204 &self.log
205 }
206
207 /// Borrow the wrapped device.
208 pub fn inner(&self) -> &D {
209 &self.inner
210 }
211}
212
213impl<D: CaDevice> CaDevice for RecordingCaDevice<D> {
214 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
215 let n = self.inner.read(buf)?;
216 if n > 0 {
217 self.log.push(LinkEvent::Rx(buf[..n].to_vec()));
218 }
219 Ok(n)
220 }
221
222 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
223 self.log.push(LinkEvent::Tx(buf.to_vec()));
224 self.inner.write(buf)
225 }
226
227 fn reset(&mut self) -> io::Result<()> {
228 self.log.push(LinkEvent::Reset);
229 self.inner.reset()
230 }
231
232 fn slot_info(&mut self) -> io::Result<SlotInfo> {
233 let si = self.inner.slot_info()?;
234 if self.last_slot != Some(si) {
235 self.log.push(LinkEvent::SlotInfo(si));
236 self.last_slot = Some(si);
237 }
238 Ok(si)
239 }
240
241 fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool> {
242 // Polls are not recorded (they would swamp the trace).
243 self.inner.poll(timeout)
244 }
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn recording_device_captures_both_directions() {
253 let inner = MockCaDevice::new([vec![0x83, 0x01, 0x01]]);
254 let mut dev = RecordingCaDevice::new(inner);
255 dev.reset().unwrap();
256 dev.write(&[0x82, 0x01, 0x01]).unwrap();
257 let mut buf = [0u8; 16];
258 dev.read(&mut buf).unwrap();
259 assert_eq!(
260 dev.log(),
261 &[
262 LinkEvent::Reset,
263 LinkEvent::Tx(vec![0x82, 0x01, 0x01]),
264 LinkEvent::Rx(vec![0x83, 0x01, 0x01]),
265 ]
266 );
267 }
268
269 #[test]
270 fn mock_records_writes_and_replays_inbound() {
271 let mut dev = MockCaDevice::new([vec![0x01, 0x02], vec![0x03]]);
272 // host writes
273 dev.write(&[0xAA, 0xBB]).unwrap();
274 dev.reset().unwrap();
275 // module frames replay in order
276 let mut buf = [0u8; 16];
277 assert_eq!(dev.read(&mut buf).unwrap(), 2);
278 assert_eq!(&buf[..2], &[0x01, 0x02]);
279 assert_eq!(dev.read(&mut buf).unwrap(), 1);
280 assert_eq!(dev.read(&mut buf).unwrap(), 0); // drained
281 assert_eq!(dev.written(), vec![0xAA, 0xBB]);
282 assert_eq!(dev.ops[1], DeviceOp::Reset);
283 }
284}