Skip to main content

dvb_ci_runtime/
driver.rs

1//! The driver — the one place I/O happens. It pumps a [`CaDevice`] against the
2//! sans-IO [`CiStack`]: reads frames in, executes the stack's [`Action`]s
3//! (writes/ioctls) out, tracks the requested poll timer, and collects
4//! [`Notification`]s for the host application.
5
6use std::io;
7use std::time::Duration;
8
9use crate::device::CaDevice;
10use crate::event::{Action, Event, HostRequest, Notification};
11use crate::stack::CiStack;
12
13/// Drives a [`CaDevice`] with the [`CiStack`].
14pub struct Driver<D: CaDevice> {
15    device: D,
16    stack: CiStack,
17    notifications: Vec<Notification>,
18    /// Delay the stack last asked to be polled after (`None` = none pending).
19    next_timer: Option<Duration>,
20    /// Read buffer for one link-layer frame.
21    buf: Vec<u8>,
22}
23
24impl<D: CaDevice> Driver<D> {
25    /// New driver over `device`, single transport connection.
26    #[must_use]
27    pub fn new(device: D) -> Self {
28        Self {
29            device,
30            stack: CiStack::new(),
31            notifications: Vec::new(),
32            next_timer: None,
33            buf: vec![0u8; 4096],
34        }
35    }
36
37    /// Borrow the underlying device (e.g. to inspect a mock's recorded ops).
38    pub fn device(&self) -> &D {
39        &self.device
40    }
41
42    /// The poll delay the stack most recently requested, if any.
43    pub fn next_timer(&self) -> Option<Duration> {
44        self.next_timer
45    }
46
47    /// Drain the notifications collected so far.
48    pub fn take_notifications(&mut self) -> Vec<Notification> {
49        core::mem::take(&mut self.notifications)
50    }
51
52    /// Bring the interface up (reset + open the transport connection).
53    pub fn init(&mut self) -> io::Result<()> {
54        let actions = self.stack.handle(Event::Host(HostRequest::Init));
55        self.run(actions)
56    }
57
58    /// Request the module descramble the services in `ca_pmt` (a serialized
59    /// `ca_pmt` APDU body, e.g. from `dvb_ci::build_ca_pmt`).
60    pub fn send_ca_pmt(&mut self, ca_pmt: &[u8]) -> io::Result<()> {
61        let actions = self
62            .stack
63            .handle(Event::Host(HostRequest::SendCaPmt(ca_pmt)));
64        self.run(actions)
65    }
66
67    /// One pump step: if the device is readable within `timeout`, read a frame
68    /// and feed it; otherwise advance the stack's timers by `timeout` (driving
69    /// the poll cadence). Returns whether a frame was processed.
70    pub fn pump(&mut self, timeout: Duration) -> io::Result<bool> {
71        if self.device.poll(timeout)? {
72            let n = self.device.read(&mut self.buf)?;
73            if n > 0 {
74                let frame = self.buf[..n].to_vec();
75                let actions = self.stack.handle(Event::Readable(&frame));
76                self.run(actions)?;
77                return Ok(true);
78            }
79        }
80        let actions = self.stack.handle(Event::Tick { elapsed: timeout });
81        self.run(actions)?;
82        Ok(false)
83    }
84
85    /// Execute the stack's actions against the device.
86    fn run(&mut self, actions: Vec<Action>) -> io::Result<()> {
87        for action in actions {
88            match action {
89                Action::Write(bytes) => self.device.write(&bytes)?,
90                Action::Reset => self.device.reset()?,
91                Action::QuerySlot => {
92                    self.device.slot_info()?;
93                }
94                Action::SetTimer { after } => self.next_timer = Some(after),
95                Action::Notify(n) => self.notifications.push(n),
96            }
97        }
98        Ok(())
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::device::{DeviceOp, MockCaDevice};
106    use dvb_ci::tpdu::tags;
107
108    #[test]
109    fn init_drives_reset_slotinfo_and_create_tc_to_device() {
110        let mut d = Driver::new(MockCaDevice::new([]));
111        d.init().unwrap();
112        let ops = &d.device().ops;
113        assert_eq!(ops[0], DeviceOp::Reset);
114        assert_eq!(ops[1], DeviceOp::SlotInfo);
115        assert!(matches!(&ops[2], DeviceOp::Write(w) if w[0] == tags::CREATE_T_C));
116    }
117
118    #[test]
119    fn reads_reply_then_polls_on_pump() {
120        // Script the module accepting the connection.
121        let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
122        let mut d = Driver::new(dev);
123        d.init().unwrap();
124        // first pump reads the C_T_C_Reply (activates the connection)
125        assert!(d.pump(Duration::from_millis(100)).unwrap());
126        // next pump has nothing to read → ticks → emits a poll write
127        assert!(!d.pump(Duration::from_millis(100)).unwrap());
128        let last = d.device().ops.last().unwrap();
129        assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
130    }
131}