import { Interface } from "./interface"; import * as Net from "net"; interface NetworkInterfaceOptions { timeout?: number; } export class NetworkInterface implements Interface { private timeout: number; private host: string; private port: number; constructor(host: string, port: number, options: NetworkInterfaceOptions = {}) { const { timeout = 3000 } = options; options = options || {}; this.timeout = timeout; this.host = host; this.port = port || 9100; } getPrinterName(): string { let name = this.host + ":" + this.port; return name; } async isPrinterConnected(): Promise { return new Promise((resolve, reject) => { var printer = Net.connect( { host: this.host, port: this.port, timeout: this.timeout, }, function () { resolve(true); printer.destroy(); } ); printer.on("error", function (error) { console.error("Printer network connection error:", error); resolve(false); printer.destroy(); }); printer.on("timeout", function () { console.error("Printer network connection timeout."); resolve(false); printer.destroy(); }); }); } async execute(buffer: Uint8Array): Promise { return new Promise((resolve, reject) => { var printer = Net.connect( { host: this.host, port: this.port, timeout: this.timeout, }, () => { printer.write(buffer, () => { resolve(); printer.destroy(); }); } ); printer.on("error", (error) => { reject(error); printer.destroy(); }); printer.on("timeout", function () { reject(new Error("Socket timeout")); printer.destroy(); }); }); } }