uem_reader/
reader.rs

1//! Readers module contains type definitions 
2//! for reader operation objects
3
4pub 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
17/// General reader type using Arc standard type
18pub type UemReader = Arc<Mutex<dyn UemReaderInternalTrait+Send>>;
19/// Vector of readers discovered using specified method
20//pub type UemReaders = Vec<UemReader>;
21
22type UemGeneralResult<T> = core::result::Result<T, UemError>;
23/// Common library result
24pub type UemResult = UemGeneralResult<()>;
25/// Library result containing returned vector of bytes
26pub type UemResultVec = UemGeneralResult<Vec<u8>>;
27/// Library result containing ISO14443a card
28pub type UemResultCardA = UemGeneralResult<UemCardIso14443A>;
29/// Library result containing ISO14443b card
30pub type UemResultCardB = UemGeneralResult<UemCardIso14443B>;
31
32impl UemCommandsTrait for UemReader {   
33    fn commands(&mut self) -> UemCommands {
34        UemCommands::new(self)
35    }
36}
37
38/// Common reader methods
39pub 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    /// Open interface with the reader
47    /// 
48    /// # Example
49    /// 
50    /// ```ignore
51    /// if uem_reader.open().is_err() {
52    ///     return;
53    /// }
54    /// ```
55    fn open(&mut self) -> UemResult {
56        self.lock().unwrap().open()
57    }
58
59    /// Close opened reader interface 
60    /// 
61    /// # Example
62    /// 
63    /// ```ignore
64    /// if uem_reader.close().is_err() {
65    ///     return;
66    /// };
67    /// ```
68    fn close(&mut self) -> core::result::Result<(), UemError> {
69        self.lock().unwrap().close()
70    }
71
72    /// Send a command to a reader and receive response
73    /// 
74    /// # Arguments
75    ///
76    /// * `command` - a vector of command bytes
77    /// 
78    /// # Returns
79    /// 
80    /// `Ok(())` on success, otherwise returns an error.
81    /// 
82    /// # Example
83    /// 
84    /// ```ignore
85    /// // Beep 1 time using command byte vector
86    /// if uem_reader.send(&vec![0x05_u8, 0x01_u8]).is_err() {
87    ///     return;
88    /// }
89    /// ```
90    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        //if ((reader != null) && reader.Reader.encryptedMode) {
111        //    rawData.write(0x00);
112        //    data = AES.encryptChannel(data, reader);
113        //    if (data == null)
114        //        return null;
115        //}
116        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));//  Err(UemError::CRC);
143        }
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        //if (reader != null) && reader.Reader._encryptedMode && (data[0] == 0x00) {
149        //    data = AES.decryptChannel(Arrays.copyOfRange(data, 1, data.length), reader);
150        //}
151        Ok(data)
152    }
153}