ble-server/PrinterDev.js

106 lines
2.5 KiB
JavaScript

const EventEmitter = require('events')
const escpos = require('escpos')
const config = require('./config.json')
const fs = require('fs')
const iconv = require('iconv-lite')
// const device = new escpos.Serial(config.printer.serial)
// const printer = new escpos.Printer(device)
// let isOpen = false
class PrinterDevice {
constructor() {
this._isOpen = false
this._device = null
this._printer = null
this._type = null // type = serial or console
}
encodeStr(str){
if(!str || typeof str != 'string') return false
return iconv.encode(str, 'big5')
}
async connect() {
let chkSerial = await new Promise((resolve, reject) => {
fs.access(config.printer.serial, err => {
if (err) return resolve(false)
return resolve(true)
})
})
if (chkSerial) {
this._device = new escpos.Serial(config.printer.serial)
this._type = 'serial'
} else {
this._device = new escpos.Console()
this._type = 'console'
}
this._printer = new escpos.Printer(this._device)
this.openSerial()
}
async openSerial() {
if (!this._device || this._type != 'serial') return
this._isOpen = await new Promise((resolve, reject) => {
this._device.open(err => {
if (err) return resolve(false)
return resolve(true)
})
})
}
async printerString(str) {
if (!this._isOpen || !this._printer) return false
this._printer.font('a')
.align('ct')
.size(1, 1)
let cmds = str.split(/__/).filter(t => t)
for (let i in cmds) {
let tmp = cmds[i]
if (tmp[0] === '&') {
switch (tmp[1]) {
case 'a':
let align = tmp.substring(2)
if (!align) break
this._printer.align(align)
break
case 's':
let size = tmp.substring(2)
let sarr = size.trim().split(',')
if (sarr != 2) break
if(!isFinite(sarr[0]) || !isFinite(sarr[1])) break
sarr = sarr.map(t => Math.floor(t))
this._printer.size(sarr[0], sarr[1])
break
}
} else {
this._printer.print(this.encodeStr(tmp))
}
}
this._printer.cut(true, config.printer.cutFeed || 4)
return true
}
async close() {
if (!this._device) return
if (this._type == 'serial') {
let self = this
await new Promise((resolve, reject) => {
self._printer.close(() => {
resolve(1)
})
})
}
}
get isOpen() {
return this._isOpen ? true : false
}
}
module.exports = new PrinterDevice()