-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathusbscanner.js
113 lines (102 loc) · 2.34 KB
/
usbscanner.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var HID = require("node-hid");
const EventEmitter = require("events");
var util = require("util");
/*
options:
{vendorId:Int, hidMap: Obj}
defaults:
{vendorId:1534, hidMap:{30: '1', 31: '2', 32: '3', 33: '4',34: '5',35: '6', 36: '7', 37: '8', 38: '9',39: '0',40: 'e'}}
*/
function usbScanner(options) {
var opts = options || {};
this.init(opts);
EventEmitter.call(this);
}
//enherit event emitter
util.inherits(usbScanner, EventEmitter);
function getDevices() {
return HID.devices();
}
usbScanner.prototype.init = function(options) {
var vendorId = options.vendorId || 1534;
var devicePath = options.devicePath || null;
//hidMap defining keyboard code to coresponding string value
this.hidMap = options.hidMap || {
4: "A",
5: "B",
6: "C",
7: "D",
8: "E",
9: "F",
10: "G",
11: "H",
12: "I",
13: "J",
14: "K",
15: "L",
16: "M",
17: "N",
18: "O",
19: "P",
20: "Q",
21: "R",
22: "S",
23: "T",
24: "U",
25: "V",
26: "W",
27: "X",
28: "Y",
29: "Z",
30: "1",
31: "2",
32: "3",
33: "4",
34: "5",
35: "6",
36: "7",
37: "8",
38: "9",
// enter - barcode escape char
39: "0",
40: "enter",
44: " ",
45: "-",
55: ".",
56: "/",
85: "*",
87: "+"
};
var scanner = devicePath
? { path: devicePath }
: getDevices().find(device => device.vendorId === vendorId);
this.device = new HID.HID(scanner.path);
// start waiting for scan events
this.startScanning();
};
usbScanner.prototype.startScanning = function() {
//empty array for barcode bytes
var bcodeBuff = [];
//string variable to hold barcode string
var aBarcode = "";
//event emitter for when newCode is read from scanner
this.device.on("data", chunk => {
//second byte of buffer is all that contains data
if (this.hidMap[chunk[2]]) {
//if not bcodeBuff escape char (40)
if (chunk[2] !== 40) {
bcodeBuff.push(this.hidMap[chunk[2]]);
} else {
//revieved escape code, join bCodebuff array and
aBarcode = bcodeBuff.join("");
bcodeBuff = [];
//emit newCode event
this.emit("data", aBarcode);
}
}
});
};
usbScanner.prototype.stopScanning = function() {
this.device.close();
};
module.exports = { usbScanner: usbScanner, getDevices: getDevices };