1pub mod usb;
5pub mod com;
6
7use crate::errors::*;
8use crate::commands::*;
9use crate::card::*;
10pub use crate::reader::usb::find_usb_readers;
11
12use std::sync::{Arc, Mutex};
13use std::{time::Duration};
14
15pub(crate) const TIMEOUT: Duration = Duration::from_secs(1);
16
17pub type UemReader = Arc<Mutex<dyn UemReaderInternalTrait+Send>>;
19type UemGeneralResult<T> = core::result::Result<T, UemError>;
23pub type UemResult = UemGeneralResult<()>;
25pub type UemResultVec = UemGeneralResult<Vec<u8>>;
27pub type UemResultCardA = UemGeneralResult<UemCardIso14443A>;
29pub type UemResultCardB = UemGeneralResult<UemCardIso14443B>;
31
32impl UemCommandsTrait for UemReader {
33 fn commands(&mut self) -> UemCommands {
34 UemCommands::new(self)
35 }
36}
37
38pub trait UemReaderInternalTrait {
40 fn open(&mut self) -> UemResult;
41 fn close(&mut self) -> core::result::Result<(), UemError>;
42 fn send(&mut self, command: &[u8]) -> UemResultVec;
43}
44
45impl UemReaderInternalTrait for UemReader {
46 fn open(&mut self) -> UemResult {
56 self.lock().unwrap().open()
57 }
58
59 fn close(&mut self) -> core::result::Result<(), UemError> {
69 self.lock().unwrap().close()
70 }
71
72 fn send(&mut self, command: &[u8]) -> UemResultVec {
91 self.lock().unwrap().send(command)
92 }
93}
94
95pub(crate) mod processing {
96 use crate::{helpers::*, reader::*};
97 pub(crate) trait CommandsCounter {
98 fn commands_count(&self) -> u8;
99 fn increment_commands(&mut self);
100 }
101
102 pub(crate) fn prepare_command(reader: &mut impl CommandsCounter, data: &[u8]) -> Vec<u8> {
103
104 let mut raw_data: Vec<u8> = vec![];
105
106 raw_data.push(0x00);
107 raw_data.push(reader.commands_count());
108 reader.increment_commands();
109
110 let mut tmp_v = vec![];
117 data.clone_into(&mut tmp_v);
118 raw_data.append(&mut tmp_v);
119
120 let mut fsc = crc16(&raw_data);
121 raw_data.append(&mut fsc);
122
123 let mut tmp_data = byte_stuff(&raw_data);
124 let mut raw_data: Vec<u8> = vec![];
125 raw_data.reserve(2 + tmp_data.len());
126 raw_data.push(0xFD);
127 raw_data.append(&mut tmp_data);
128 raw_data.push(0xFE);
129 return raw_data;
130 }
131
132 pub(crate) fn parse_response(raw_data: &Vec<u8>) -> UemResultVec {
133 let raw_data = unbyte_stuff(raw_data);
134 if (raw_data[0] & 0xFF) != 0xFD {
135 return Err(UemError::ReaderUnsuccessful(UemInternalError::Protocol, None));
136 }
137 if (raw_data[raw_data.len()-1] & 0xFF) != 0xFE {
138 return Err(UemError::ReaderUnsuccessful(UemInternalError::Protocol, None));
139 }
140 let fsc = crc16(&raw_data[1..raw_data.len()-3]);
141 if (fsc[0] & 0xFF) != (raw_data[raw_data.len()-3] & 0xFF) {
142 return Err(UemError::ReaderUnsuccessful(UemInternalError::Crc, None));}
144 if (fsc[1] & 0xFF) != (raw_data[raw_data.len()-2] & 0xFF) {
145 return Err(UemError::ReaderUnsuccessful(UemInternalError::Crc, None));
146 }
147 let data = raw_data[3..raw_data.len()-3].to_vec();
148 Ok(data)
152 }
153}