use crate::{
Command, Error, Port, Response, StatusWord,
resend::{Resends, short_le},
};
const RESPONSE_PENDING: u8 = 0x61;
const SM_DATA_MISSING: StatusWord = StatusWord(0x6987);
const MAX_GET_RESPONSES: usize = 256;
const PLAIN_CLA: u8 = 0x00;
pub(crate) trait CommandChannel {
fn transmit(&mut self, command: &Command) -> Result<Response, Error>;
}
pub(crate) struct PlainChannel<'a> {
port: &'a mut dyn Port,
}
impl<'a> PlainChannel<'a> {
pub(crate) fn new(port: &'a mut dyn Port) -> Self {
Self { port }
}
}
impl CommandChannel for PlainChannel<'_> {
fn transmit(&mut self, command: &Command) -> Result<Response, Error> {
let mut data = Vec::new();
let mut get_responses = 0;
let mut resends = Resends::default();
let mut channel_dropped = false;
loop {
let sent = resends.current(command);
let response = Response::parse(&self.port.transmit(&sent.to_bytes()?)?)?;
let plain = sent.cla == PLAIN_CLA;
if response.status == SM_DATA_MISSING && plain {
if channel_dropped {
return Err(Error::Status(response.status));
}
channel_dropped = true;
continue;
}
if Resends::is_wrong_length(response.status) && plain {
resends.resend_with_le(command, response.status)?;
continue;
}
data.extend(response.data);
let [sw1, sw2] = response.status.0.to_be_bytes();
if sw1 != RESPONSE_PENDING {
return Ok(Response {
data,
status: response.status,
});
}
if get_responses == MAX_GET_RESPONSES {
return Err(Error::Status(response.status));
}
get_responses += 1;
resends.replace_with(get_response(sw2));
}
}
}
fn get_response(le: u8) -> Command {
Command {
cla: PLAIN_CLA,
ins: 0xC0,
p1: 0x00,
p2: 0x00,
data: vec![],
le: Some(short_le(le)),
}
}
#[cfg(test)]
mod tests;