-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreader.ts
65 lines (48 loc) · 1.69 KB
/
reader.ts
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
import SmartCard from "./cards/smartcard";
export interface Apdu {
Cla : number;
Ins : number;
P1 : number;
P2 : number;
Le : number;
Lc : number;
}
export interface ApduResponse {
SW : Array<number>;
Data? : Array<number>;
}
export default class Reader {
private readonly _defaultTimeout : number;
constructor(private _pcscReader : any) {
this._defaultTimeout = 8000;
}
get name() {
return this._pcscReader.name;
}
async sendApdu(card : SmartCard, cmd : Apdu, dataIn : Array<number>, timeout? : number) : Promise<ApduResponse> {
if (timeout == null)
timeout = this._defaultTimeout;
return new Promise<ApduResponse>((resolve,reject) => {
let cmdTimeout = setTimeout(() => {
reject(`Timeout: no apdu response after ${timeout}ms`);
}, timeout);
let apduBuffer : Array<number> = [cmd.Cla, cmd.Ins, cmd.P1, cmd.P2, cmd.Lc];
if (dataIn)
apduBuffer.push(...dataIn);
this._pcscReader.transmit(Buffer.from(apduBuffer), cmd.Le + 2, card.protocol, function(err, data) {
if (err) {
reject(`Apdu error: ${err}`);
} else {
let bytesArray : Array<number> = [...data];
let sw = [ bytesArray[bytesArray.length-2], bytesArray[bytesArray.length-1]];
let receivedData = bytesArray.slice(0,bytesArray.length-2);
resolve({SW: sw,Data: receivedData});
}
});
});
}
close () {
if (this._pcscReader)
this._pcscReader.close();
}
}