This repository was archived by the owner on May 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (81 loc) · 2.28 KB
/
Copy pathindex.js
File metadata and controls
102 lines (81 loc) · 2.28 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const HID = require('node-hid').HID;
const devices = require('node-hid').devices();
const EventEmitter = require('events');
const hidMap = require('./hidmap');
class UsbScanner extends EventEmitter {
constructor(options) {
options = options || {};
let {
vendorID = undefined,
productID = undefined,
path = undefined,
vCardString = true,
vCardSeperator = '|'
} = options;
super();
this.vendorID = vendorID;
this.productID = productID;
this.path = path;
this._vCardString = vCardString;
this._vCardSeperator = vCardSeperator;
this._hidMap = hidMap.standard;
this._hidMapShift = hidMap.shift;
// Bind 'this' to the methods
this.startScanning = this.startScanning.bind(this);
}
static showDevices() {
return devices;
}
startScanning() {
try {
if(this.path) this.hid = new HID(path);
else if (this.vendorID && this.productID) this.hid = new HID(this.vendorID, this.productID);
else throw 'Device cannot be found, please supply a path or VID & PID';
} catch(error) {
this.emit('error', error);
}
let scanResult = [];
let vCard = [];
this.hid.on('data', (data) => {
const modifierValue = data[0];
const characterValue = data[2];
if (characterValue !== 0) {
if (modifierValue === 2 || modifierValue === 20) {
scanResult.push(this._hidMapShift[characterValue]);
} else if (characterValue !== 40) {
scanResult.push(this._hidMap[characterValue]);
} else if (characterValue === 40) {
let barcode = scanResult.join('');
scanResult = [];
barcode = removeUTF8(barcode);
if (this._vCardString) {
if (barcode === 'BEGIN:VCARD') {
vCard.push(barcode);
} else if (barcode === 'END:VCARD') {
vCard.push(barcode);
vCard = vCard.join(this._vCardSeperator);
this.emit('data', vCard);
vCard = [];
} else if (vCard.length > 0 ) {
vCard.push(barcode);
} else this.emit('data', barcode);
} else {
this.emit('data', barcode);
}
}
}
});
}
stopScanning() {
this.hid.removeAllListeners('data');
this.hid.close();
}
}
function removeUTF8(barcode) {
let utf8 = barcode.slice(0, 7);
if (utf8 === '\\000026') {
barcode = barcode.slice(7);
return barcode;
} else return barcode;
}
module.exports = UsbScanner;