Skip to content

Commit

Permalink
add connection timeout to network device
Browse files Browse the repository at this point in the history
  • Loading branch information
Wesam Alzahir authored and lsongdev committed Aug 8, 2022
1 parent 0311321 commit 8d9951b
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion packages/network/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ import {Adapter} from "escpos-adapter";
export default class Network extends Adapter<[device: net.Socket]> {
private readonly address: string;
private readonly port: number;
private readonly timeout: number;
private readonly device: net.Socket;

/**
* @param {[type]} address
* @param {[type]} port
*/
constructor(address: string, port = 9100) {
constructor(address: string, port = 9100, timeout = 30000) {
super();
this.address = address;
this.port = port;
this.timeout = timeout;
this.device = new net.Socket();
}

Expand All @@ -27,12 +29,21 @@ export default class Network extends Adapter<[device: net.Socket]> {
* @return
*/
open(callback?: (error: Error | null, device: net.Socket) => void) {
// start timeout on open
const connection_timeout = setTimeout(() => {
this.device.destroy();
callback && callback(
new Error(`printer connection timeout after ${this.timeout}ms`), this.device
);
}, this.timeout);

// connect to net printer by socket (port, ip)
this.device.on("error", (err) => {
callback && callback(err, this.device);
}).on('data', buf => {
// console.log('printer say:', buf);
}).connect(this.port, this.address, (err?: Error | null) => {
clearInterval(connection_timeout);
this.emit('connect', this.device);
callback && callback(err ?? null, this.device);
});
Expand Down

0 comments on commit 8d9951b

Please sign in to comment.