-
Notifications
You must be signed in to change notification settings - Fork 56
/
Device.js
83 lines (71 loc) · 1.95 KB
/
Device.js
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
'use strict';
import Card from './Card';
import { EventEmitter } from 'events';
import pino from 'pino';
const logger = pino({ name: 'Device' });
class Device extends EventEmitter {
constructor(reader) {
super();
logger.debug(`new Device(${reader})`);
this.reader = reader;
this.name = reader.name;
this.card = null;
const isCardInserted = (changes, reader, status) => {
return (
changes & reader.SCARD_STATE_PRESENT &&
status.state & reader.SCARD_STATE_PRESENT
);
};
const isCardRemoved = (changes, reader, status) => {
return (
changes & reader.SCARD_STATE_EMPTY &&
status.state & reader.SCARD_STATE_EMPTY
);
};
const cardInserted = (reader, status) => {
reader.connect({ share_mode: 2 }, (err, protocol) => {
if (err) {
this.emit('error', err);
} else {
this.card = new Card(this, status.atr, protocol);
this.emit('card-inserted', { device: this, card: this.card });
}
});
};
const cardRemoved = (reader) => {
const name = reader.name;
reader.disconnect(reader.SCARD_LEAVE_CARD, (err) => {
if (err) {
this.emit('error', err);
} else {
this.emit('card-removed', { name, card: this.card });
this.card = null;
}
});
};
reader.on('status', (status) => {
const changes = reader.state ^ status.state;
if (changes) {
if (isCardRemoved(changes, reader, status)) {
cardRemoved(reader);
} else if (isCardInserted(changes, reader, status)) {
cardInserted(reader, status);
}
}
});
}
transmit(data, res_len, protocol, cb) {
try {
this.reader.transmit(data, res_len, protocol, cb);
} catch (err) {
logger.warn(`transmit`, err);
}
}
getName() {
return this.name;
}
toString() {
return `${this.getName()}`;
}
}
export default Device;