import { Uuid } from 'pc-component-v3'; import Common from './Common.js'; export default { webSocket: null, // 获取mac地址 getMacAddress: function () { const _self = this; const command = { id: Uuid.createUUID(), command: 'getMacAddress', }; const commandStr = JSON.stringify(command); return new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr); }); }, // 获取打印机 getPrinters: function () { const _self = this; const command = { id: Uuid.createUUID(), command: 'getPrinters', }; const commandStr = JSON.stringify(command); return new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr); }); }, // 执行打印 print: function (prnData) { const _self = this; const command = { id: Uuid.createUUID(), command: 'print', data: prnData, }; const commandStr = JSON.stringify(command); return new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr); }); }, // 取消打印 cancelAllTask: function (prnData) { const _self = this; const command = { id: Uuid.createUUID(), command: 'cancelAllTask', data: prnData, }; const commandStr = JSON.stringify(command); return new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr); }); }, // 连接node red的websocket connectNodeRed: function (resolve, reject, commandStr) { const _self = this; let printers = null; let socketUrl = 'ws://127.0.0.1:10092'; _self.webSocket = new WebSocket(socketUrl); _self.webSocket.onopen = function (event) { console.log('打印 Websocket 连接成功。'); if (commandStr != null && commandStr.length > 0) { _self.sendCommand(commandStr); } else { _self.close(); } }; _self.webSocket.onclose = function (event) { console.log('打印 Websocket 断开连接。'); resolve(printers); }; _self.webSocket.onerror = function (event) { console.log('打印 Websocket 出错。'); _self.close(); reject(); }; _self.webSocket.onmessage = function (event) { const data = JSON.parse(event.data); printers = data; _self.close(); }; }, // WebSocket 发送指令 sendCommand: function (command) { if (this.webSocket) { this.webSocket.send(command); } }, // 关闭Websocket close: function () { if (this.webSocket) { this.webSocket.close(); this.webSocket = null; }; }, getRootPath: function () { var protocol = window.location.protocol; var host = window.location.hostname; var path = protocol + host; return path; }, // 查询所有模板信息 queryTemplates: function () { var requestUrl = 'CustomerCloudPrintTemplateResource/querySimpleAllTemplate'; return new Promise((resolve, reject) => { $.ajax({ url: Common.getApiURL(requestUrl), type: 'get', contentType: 'application/json', beforeSend: function (request) { Common.addTokenToRequest(request); }, success: function (data) { resolve(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { reject(XMLHttpRequest); }, }); }); }, };