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 routes from '../routes.js'; import { pathToFileURL } from 'url'; import path from 'path'; import EventEmitter from 'events'; import { getResourcePath } from '../utils/runtime.js'; // 框架基础类 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); this._initWmiPrinterMonitor(); this.app.on('printerWmiStatusChange', (data) => { console.log('打印机状态变化事件触发,数据:', data); this.services.printer.getWindowsPrinters(); }); }); 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 { const ps = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath], { stdio: ['ignore', 'pipe', 'pipe'] }); let lastStatus = {}; 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) => { console.warn(`[WMI Printer Monitor] exited with code ${code}`); }); } catch (e) { console.error('[WMI Printer Monitor] failed to start:', e); } } router(req, res) { this.ctx.request = req; this.ctx.response = res; const match = routes.find(r => r.method === req.method && r.path === req.url); if (match) { const parts = match.controller.split('.'); const action = parts.pop(); // 最后一个部分是方法名 const controllerPath = parts.join('.'); // 其余部分合并为控制器路径 console.log('匹配到路由:', match.method, match.path, '=>', controllerPath, action); const ctrl = this.getController(controllerPath); // 加载控制器 if (ctrl && typeof ctrl[action] === 'function') { ctrl[action](req, res); } else { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('控制器或方法不存在'); } } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } } async init() { await this._loadServices(); await this._loadControllers(); } getConfig() { return this.config; } setConfig(newConfig) { this.config = newConfig; return this.configUtil.write(newConfig); } getController(name) { console.log('获取控制器:', name); console.log('当前控制器列表:', Object.keys(this.ctx.controllers)); return this.ctx.controllers[name]; } getService(name) { return this.ctx.services[name]; } createContext(req, res) { // 构建 ctx 上下文对象 return { app: this.app, config: this.config, req, res, controllers: this.ctx.controllers // 可扩展更多上下文属性 }; } // 可扩展更多框架基础能力 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)); } async _loadControllers() { // 递归加载 controllers 目录下所有 js 文件,按目录结构组装对象 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); 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.ctx.controllers = await walk(path.join(__dirname, '../controllers')); console.log('[WSServer] 已加载控制器:', Object.keys(this.ctx.controllers)); } } export default new Main();