2026-04-09 01:36:49 +08:00

71 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
class PrintService extends Service {
// 发送信息到打印电脑
async sendToComputer({ warehouse, computerId, data }) {
// 发送指令更新打印机状态
const printServiceUrl = this.ctx.app.config.printService.url;
// 先获取redis中打印机列表
let printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`);
let lastUpdateTime = 0;
if (printerListResult) {
// 记录上次更新时间,避免频繁发送更新指令
const printerData = JSON.parse(printerListResult);
lastUpdateTime = printerData.updatedAt || 0;
}
// 不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表
await this.ctx.curl(`${printServiceUrl}/sendToRoom`, {
method: 'POST',
contentType: 'json',
data: { warehouse, computerId, method: 'printer.getWindowsPrinters', data: {} },
dataType: 'json',
});
// 等待异步获取打印机列表结果,最长等待5秒
const startTime = Date.now();
while (Date.now() - startTime < 5000) {
await new Promise(resolve => setTimeout(resolve, 10)); // 每10ms检查一次
printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`);
const printerData = JSON.parse(printerListResult);
if (printerData.updatedAt && printerData.updatedAt > lastUpdateTime) {
// 如果更新了打印机列表,跳出循环
break;
}
}
// 从redis获取打印机
printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`);
const printerList = JSON.parse(printerListResult);
if (!printerList || !printerList.data || printerList.data.length === 0) {
return { success: false, error: '未找到对应的打印机', detail: `computerId: ${computerId} 的打印机列表不存在` };
}
const { printer } = data;
const printerInfo = printerList.data.find(p => p.name === printer);
if (!printerInfo) {
return { success: false, error: `打印台没有打印机 ${printer}`, detail: `computerId: ${computerId} 的打印机列表中不存在 printer: ${printer}` };
}
if (printerInfo.workOffline === 'TRUE') {
return { success: false, error: `打印机 ${printer} 处于脱机状态`, detail: `computerId: ${computerId} 的打印机 ${printer} 当前处于离线状态` };
}
try {
const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, {
method: 'POST',
contentType: 'json',
data: { warehouse, computerId, method: 'printer.print', data },
dataType: 'json',
});
return res.data;
} catch (err) {
return { success: false, error: '打印服务通讯失败', detail: err.message };
}
}
async test() {
const grabnum = 'B1157389';
const datas = await this.app.wsdl('print', [ 5400, grabnum, 'caige' ]);
this.sendToComputer({ warehouse: '1000028', computerId: '1', data: datas });
}
}
module.exports = PrintService;