-
Notifications
You must be signed in to change notification settings - Fork 0
/
printerCommunication.js
55 lines (48 loc) · 1.33 KB
/
printerCommunication.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
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
class Printer {
constructor(port, baudRate) {
this.port = port;
this.baudRate = baudRate;
this.serialPort = new SerialPort(this.port, { baudRate: this.baudRate });
this.parser = this.serialPort.pipe(new Readline({ delimiter: '\n' }));
}
connect() {
return new Promise((resolve, reject) => {
this.serialPort.on('open', () => {
console.log('Connected to printer on', this.port);
resolve();
});
this.serialPort.on('error', (err) => {
console.error('Failed to connect to printer:', err);
reject(err);
});
});
}
sendCommand(command) {
return new Promise((resolve, reject) => {
this.serialPort.write(command + '\n', (err) => {
if (err) {
console.error('Failed to send command to printer:', err);
reject(err);
} else {
console.log('Command sent:', command);
resolve();
}
});
});
}
onData(callback) {
this.parser.on('data', callback);
}
close() {
this.serialPort.close((err) => {
if (err) {
console.error('Failed to close printer connection:', err);
} else {
console.log('Printer connection closed');
}
});
}
}
module.exports = Printer;