import WSServer from './wsServer.js'; import configUtil from '../utils/config.js'; import PrinterComponentCore from './printerComponentCore.js'; import PrinterComponentMessageHandler from './printerComponentMessageHandler.js'; import WSClient from './wsClient.js'; import fs from 'fs'; import { pathToFileURL } from 'url'; import path from 'path'; import EventEmitter from 'events'; import { getResourcePath } from '../utils/runtime.js'; function hasProcessArg(flag) { return process.argv.includes(flag); } // 框架基础类 Main class Main extends EventEmitter { constructor() { super(); if (Main.instance) { return Main.instance; } this.config = configUtil.read(); this.app = this; this.info = null; this.isBind = false; // 绑定状态 this.ctx = {}; this.services = {}; this.printerComponents = new PrinterComponentCore(this); this.printerComponents.initAll(); // 初始化打印组件消息处理对象 this.printerComponentMessageHandler = new PrinterComponentMessageHandler(this, this.printerComponents); this.printerComponentMessageHandler.init(); // 监听 WMI 打印机状态变化 //console.log(`ws服务器已启动,监听端口: ${this.config.wsPort}`); this.init().then(() => { //console.log('框架初始化完成'); //console.log('初始化services完成,当前服务列表:', Object.keys(this.services)); this.wsClient = new WSClient(this.config.remoteWs.url, { reconnectInterval: this.config.remoteWs.reconnectInterval || 3000 }, this); this.wsServer = new WSServer(this.config.wsPort, this); console.log('[Main] 本地 WS 服务已启动,端口:', this.config.wsPort); this._initWmiPrinterMonitor(); this.app.on('printerWmiStatusChange', (data) => { //console.log('打印机状态变化事件触发,数据:', data); this.services.printer.getWindowsPrinters(); }); }); this.app.on("kuaishouMessage", (data) => { console.log("收到快手打印组件消息,数据:", data); }); Main.instance = this; return this; } async _initWmiPrinterMonitor() { // Use child_process to start PowerShell polling script, listen for printer status changes const { spawn } = await import('child_process'); const scriptPath = getResourcePath('printer.ps1'); try { let lastStatus = {}; const startMonitor = (useBypass = false) => { const args = useBypass ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath] : ['-NoProfile', '-File', scriptPath]; const ps = spawn('powershell.exe', args, { stdio: ['ignore', 'pipe', 'pipe'] }); ps.stdout.on('data', (data) => { const lines = data.toString().split(/\r?\n/).filter(Boolean); for (const line of lines) { // Parse format: 15:15:46 PrinterName: Status (Online/Offline) const match = line.match(/^(\d{2}:\d{2}:\d{2}) (.+?): (.+?) \((Online|Offline)\)$/); if (match) { const [, time, name, status, online] = match; const key = name; if (lastStatus[key] !== status + online) { lastStatus[key] = status + online; this.app.emit('printerWmiStatusChange', { name, status, online, time }); } } } }); ps.stderr.on('data', (data) => { console.error('[WMI Printer Monitor][stderr]', data.toString()); }); ps.on('error', (err) => { console.error('[WMI Printer Monitor][error]', err); }); ps.on('exit', (code) => { if (!useBypass && code !== 0) { console.warn('[WMI Printer Monitor] no-bypass launch failed, retrying with ExecutionPolicy Bypass once'); startMonitor(true); return; } console.warn(`[WMI Printer Monitor] exited with code ${code}`); }); }; startMonitor(false); } catch (e) { console.error('[WMI Printer Monitor] failed to start:', e); } } async init() { await this._loadServices(); } async restartBackendRuntime(options = {}) { const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 3001; // 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。 if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) { return { wsPort }; } this.config.wsPort = wsPort; if (this.wsClient) { this.wsClient.close(); if (typeof this.wsClient._connect === 'function') { this.wsClient._connect(); } } return { wsPort }; } getConfig() { return this.config; } setConfig(newConfig) { this.config = newConfig; return this.configUtil.write(newConfig); } getService(name) { return this.ctx.services[name]; } // 可扩展更多框架基础能力 async _loadServices() { const walk = async (dir) => { const result = {}; const files = fs.readdirSync(dir); for (const file of files) { const fullPath = path.resolve(path.join(dir, file)); const stat = fs.statSync(fullPath); if (stat.isDirectory()) { result[file] = await walk(fullPath); } else if (file.endsWith('.js')) { const name = path.basename(file, '.js'); const fileUrl = pathToFileURL(fullPath).href; console.log('[WSServer] 动态 import 路径:', fullPath, fileUrl); try { const mod = await import(fileUrl); // 自动实例化导出的类 if (mod.default && typeof mod.default === 'function') { result[name] = new mod.default(); } else { result[name] = mod.default; } } catch (e) { console.error('[WSServer] import try/catch 错误:', fileUrl, e); } } } return result; }; // 使用 pathToFileURL 修复路径解析 console.log("import.meta.url", import.meta.url); const __dirname = path.dirname(decodeURIComponent(new URL(import.meta.url).pathname.replace(/^\//, ''))); this.services = await walk(path.join(__dirname, '../services')); console.log('[WSServer] 已加载服务:', Object.keys(this.services)); } } export default new Main();