/** * node-red EPC 发卡程序 */ var Uuid = require('../../common/Uuid.js').default; export default { webSocket: '', // websocket对象 socketUrl: 'ws://127.0.0.1:18800/api/ws/print', // websocket客户端地址 /** * 打印单张EPC */ printSingleEpc: function (printerName, epc) { if (epc == null || epc.length == 0) { let promise = new Promise((resolve, reject) => { reject({ success: false, message: '打印数据中没有EPC的定义。', }); }); return promise; } var _self = this; var commandData = { id: Uuid.createUUID(), printerName: printerName, command: 'writeEpc', epc: epc, }; var commandStr = JSON.stringify(commandData); let promise = new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr); }); return promise; }, readEpc: function (printerName) { var _self = this; var commandData = { id: Uuid.createUUID(), printerName: printerName, command: 'readEpc', }; var commandStr = JSON.stringify(commandData); var promise = new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr, null); }); return promise; }, /** * 恢复标签,清除密码区域 */ resetTag: function(printerName){ var _self = this; var commandData = { id: Uuid.createUUID(), printerName: printerName, command: 'resetTag', }; var commandStr = JSON.stringify(commandData); var promise = new Promise((resolve, reject) => { _self.connectNodeRed(resolve, reject, commandStr, null); }); return promise; }, // 连接node red的websocket connectNodeRed: function (resolve, reject, commandStr) { var _self = this; _self.webSocket = new WebSocket(this.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 断开连接。'); }; _self.webSocket.onerror = function (event) { console.log('打印 Websocket 出错。'); _self.close(); reject({ success: false, message: '打印 Websocket 出错。' + event.data, }); }; _self.webSocket.onmessage = function (event) { var data = JSON.parse(event.data); console.log(data); resolve(data); _self.close(); }; }, /** * WebSocket 发送指令 * @param {指令} command */ sendCommand: function (command) { if (this.webSocket) { this.webSocket.send(command); } }, /** * 关闭Websocket */ close: function () { if (this.webSocket) { this.webSocket.close(); this.webSocket = null; }; }, };