1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! The driver — the one place I/O happens. It pumps a [`CaDevice`] against the
//! sans-IO [`CiStack`]: reads frames in, executes the stack's [`Action`]s
//! (writes/ioctls) out, tracks the requested poll timer, and collects
//! [`Notification`]s for the host application.
use std::io;
use std::time::Duration;
use crate::device::CaDevice;
use crate::event::{Action, Event, HostRequest, Notification};
use crate::stack::CiStack;
/// Drives a [`CaDevice`] with the [`CiStack`].
pub struct Driver<D: CaDevice> {
device: D,
stack: CiStack,
notifications: Vec<Notification>,
/// Delay the stack last asked to be polled after (`None` = none pending).
next_timer: Option<Duration>,
/// Read buffer for one link-layer frame.
buf: Vec<u8>,
}
impl<D: CaDevice> Driver<D> {
/// New driver over `device`, single transport connection.
#[must_use]
pub fn new(device: D) -> Self {
Self {
device,
stack: CiStack::new(),
notifications: Vec::new(),
next_timer: None,
buf: vec![0u8; 4096],
}
}
/// Borrow the underlying device (e.g. to inspect a mock's recorded ops).
pub fn device(&self) -> &D {
&self.device
}
/// The poll delay the stack most recently requested, if any.
pub fn next_timer(&self) -> Option<Duration> {
self.next_timer
}
/// Drain the notifications collected so far.
pub fn take_notifications(&mut self) -> Vec<Notification> {
core::mem::take(&mut self.notifications)
}
/// Bring the interface up (reset + open the transport connection).
pub fn init(&mut self) -> io::Result<()> {
let actions = self.stack.handle(Event::Host(HostRequest::Init));
self.run(actions)
}
/// Request the module descramble the services in `ca_pmt` (a serialized
/// `ca_pmt` APDU body, e.g. from `dvb_ci::build_ca_pmt`).
pub fn send_ca_pmt(&mut self, ca_pmt: &[u8]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::SendCaPmt(ca_pmt)));
self.run(actions)
}
/// Descramble the services in a PMT section: the stack filters the PMT's
/// `CA_descriptor`s to the CAM's advertised CAIDs and sends a `ca_pmt`
/// (`list_management = only`, `cmd_id = ok_descrambling`). The outcome
/// surfaces as [`Notification::CaPmtReply`]. Call after the CAM is ready and
/// its `ca_info` has been received (otherwise no CAID filter is applied).
pub fn descramble(&mut self, pmt_section: &[u8]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::Descramble(pmt_section)));
self.run(actions)
}
/// Descramble a set of programmes in one CA-PMT list (`first`/`more`/`last`),
/// replacing any previously selected set. Each element is a raw PMT section.
pub fn descramble_programs(&mut self, pmt_sections: &[&[u8]]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::DescramblePrograms(pmt_sections)));
self.run(actions)
}
/// Add one programme to the descrambled set (`list_management = add`) without
/// re-listing the others — for a capacity manager adding a viewer's service.
pub fn add_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::AddProgram(pmt_section)));
self.run(actions)
}
/// Remove one programme from the descrambled set (`list_management = update`,
/// `cmd_id = not_selected`) — tells the CAM to stop descrambling it.
pub fn remove_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::RemoveProgram(pmt_section)));
self.run(actions)
}
/// Answer an MMI menu/list by 1-based `choice_ref` (0 = back/cancel).
pub fn mmi_menu_answer(&mut self, choice_ref: u8) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::MmiMenuAnswer(choice_ref)));
self.run(actions)
}
/// Answer an MMI enquiry with the user's input (EN 300 468 Annex A bytes).
pub fn mmi_enquiry_answer(&mut self, text: &[u8]) -> io::Result<()> {
let actions = self
.stack
.handle(Event::Host(HostRequest::MmiEnquiryAnswer(text)));
self.run(actions)
}
/// Abort the current MMI dialogue (`answ` with `answ_id = cancel`).
pub fn mmi_cancel(&mut self) -> io::Result<()> {
let actions = self.stack.handle(Event::Host(HostRequest::MmiCancel));
self.run(actions)
}
/// Ask the module to open its MMI menu (`enter_menu`) — e.g. to read card /
/// entitlement info from the module's own menus.
pub fn enter_menu(&mut self) -> io::Result<()> {
let actions = self.stack.handle(Event::Host(HostRequest::EnterMenu));
self.run(actions)
}
/// One pump step: if the device is readable within `timeout`, read a frame
/// and feed it; otherwise advance the stack's timers by `timeout` (driving
/// the poll cadence). Returns whether a frame was processed.
pub fn pump(&mut self, timeout: Duration) -> io::Result<bool> {
if self.device.poll(timeout)? {
let n = self.device.read(&mut self.buf)?;
if n > 0 {
let frame = self.buf[..n].to_vec();
let actions = self.stack.handle(Event::Readable(&frame));
self.run(actions)?;
return Ok(true);
}
}
let actions = self.stack.handle(Event::Tick { elapsed: timeout });
self.run(actions)?;
Ok(false)
}
/// Execute the stack's actions against the device.
fn run(&mut self, actions: Vec<Action>) -> io::Result<()> {
for action in actions {
match action {
Action::Write(bytes) => self.device.write(&bytes)?,
Action::Reset => self.device.reset()?,
Action::QuerySlot => {
self.device.slot_info()?;
}
Action::SetTimer { after } => self.next_timer = Some(after),
Action::Notify(n) => self.notifications.push(n),
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::device::{DeviceOp, MockCaDevice};
use dvb_ci::tpdu::tags;
#[test]
fn init_drives_reset_slotinfo_and_create_tc_to_device() {
let mut d = Driver::new(MockCaDevice::new([]));
d.init().unwrap();
let ops = &d.device().ops;
assert_eq!(ops[0], DeviceOp::Reset);
assert_eq!(ops[1], DeviceOp::SlotInfo);
assert!(matches!(&ops[2], DeviceOp::Write(w) if w[0] == tags::CREATE_T_C));
}
#[test]
fn reads_reply_then_polls_on_pump() {
// Script the module accepting the connection.
let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
let mut d = Driver::new(dev);
d.init().unwrap();
// first pump reads the C_T_C_Reply (activates the connection)
assert!(d.pump(Duration::from_millis(100)).unwrap());
// next pump has nothing to read → ticks → emits a poll write
assert!(!d.pump(Duration::from_millis(100)).unwrap());
let last = d.device().ops.last().unwrap();
assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
}
}