forked from PhantomRay/dymo-scale-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
121 lines (105 loc) · 3.57 KB
/
app.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
114
115
116
117
118
119
120
121
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
var config = require('./config'),
HID = require('node-hid'),
usb = require('usb'),
log4js = require('log4js'),
util = require('util'),
server = require('./server').start();
log4js.configure(config.log);
var logger = log4js.getLogger();
logger.info('started in ' + process.env.NODE_ENV + ' mode');
var reading = false,
interval,
vid = 0x922,
pid = 0x8003,
msg = '';
startReading();
usb.on('attach', function (device) {
if (device.deviceDescriptor.idVendor === vid && device.deviceDescriptor.idProduct === pid) {
msg = 'Dymo M10 attached';
logger.info(msg);
server.subscriber.emit('message', {
type: 'status',
code: 'connected',
content: msg
});
interval = setInterval(startReading, 1000);
}
});
usb.on('detach', function (device) {
if (device.deviceDescriptor.idVendor === vid && device.deviceDescriptor.idProduct === pid) {
msg = 'Dymo M10 detached';
logger.warn(msg);
server.subscriber.emit('message', {
type: 'status',
code: 'disconnected',
content: msg
});
reading = false;
clearInterval(interval);
}
});
function startReading() {
if (reading) return;
try {
var d = new HID.HID(vid, pid);
reading = true;
d.on('data', function (data) {
var buf = new Buffer(data);
logger.trace(util.format('0: %s\t0: %s\t0: %s\t0: %s', buf[0], buf[1], buf[2], buf[3]));
var grams = buf[4] + (256 * buf[5]);
if (buf[1] === 5) {
msg = 'TARE IS ON';
logger.warn(msg);
server.subscriber.emit('message', {
type: 'status',
code: 'tare',
content: msg
});
} else if (grams > 0 && buf[3] === 255) { // in ounce
msg = 'Please switch to gram';
logger.warn(msg);
server.subscriber.emit('message', {
type: 'status',
code: 'ounce',
content: msg
});
} else {
logger.debug(grams + ' grams');
server.subscriber.emit('message', {
type: 'weight',
content: grams
});
}
});
d.on('error', function (err) {
if (!/could not read from HID device/.test(err.message)) {
logger.error(err);
server.subscriber.emit('message', {
type: 'status',
code: 'disconnected',
content: err.message
});
}
reading = false;
d.close();
});
} catch (err) {
if (/cannot open device/.test(err.message)) {
msg = 'Dymo M10 cannot be found';
server.subscriber.emit('message', {
type: 'status',
code: 'disconnected',
content: msg
});
logger.warn(msg);
} else {
logger.error(err);
server.subscriber.emit('message', {
type: 'status',
code: 'unknown',
message: err.message
});
}
}
}