feat: 饭卡打印助手 Flutter 版(Phase 1/2:协议服务器 + macOS CUPS 真机打印)
- 协议与 C# 版 card-printer-agent 逐字段对齐(38200-38202 顺延、CORS *、串行任务队列、30 分钟保留) - macOS CUPS 后端:lpoptions 队列发现 + lp 参数列表提交(LC_ALL=C 防本地化粘连坑) - --mock 模拟模式 + bin/agent.dart headless 入口 + 测试卡生成工具 - 真机验收:HiTi CS-200e status 就绪 + 真实出卡;macOS 通用二进制构建通过 - App Sandbox 已关闭(服务需绑回环端口并调用 lp 子进程);zaxprint URL scheme 已注册
This commit is contained in:
commit
689a07ca44
46 files changed
+2986
No files matched your search
@@ -0,0 +1,87 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'print/backend.dart';
|
||||
import 'print/mock_backend.dart';
|
||||
import 'server/http_server.dart';
|
||||
import 'server/print_queue.dart';
|
||||
|
||||
/// 启动参数:--mock 模拟打印;--port=NNN / --port NNN 指定监听端口(默认 38200-38202 顺延)。
|
||||
class AgentOptions {
|
||||
AgentOptions({this.mock = false, this.port});
|
||||
|
||||
final bool mock;
|
||||
final int? port;
|
||||
|
||||
factory AgentOptions.parse(List<String> args) {
|
||||
var mock = false;
|
||||
int? port;
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
final arg = args[i];
|
||||
if (arg == '--mock') {
|
||||
mock = true;
|
||||
} else if (arg.startsWith('--port=')) {
|
||||
port = int.tryParse(arg.substring('--port='.length));
|
||||
} else if ((arg == '--port' || arg == '-p') && i + 1 < args.length) {
|
||||
port = int.tryParse(args[++i]);
|
||||
}
|
||||
}
|
||||
return AgentOptions(mock: mock, port: port);
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行日志环形缓冲(GUI 展示用),同时打到 stdout。
|
||||
class AgentLog {
|
||||
final lines = <String>[];
|
||||
final _controller = StreamController<String>.broadcast();
|
||||
|
||||
Stream<String> get stream => _controller.stream;
|
||||
|
||||
void write(String line) {
|
||||
final stamped = '${DateTime.now().toIso8601String().substring(11, 19)} $line';
|
||||
lines.add(stamped);
|
||||
if (lines.length > 500) {
|
||||
lines.removeRange(0, lines.length - 500);
|
||||
}
|
||||
// ignore: avoid_print
|
||||
print(stamped);
|
||||
_controller.add(stamped);
|
||||
}
|
||||
|
||||
void dispose() => _controller.close();
|
||||
}
|
||||
|
||||
/// 助手核心:组合打印后端、任务队列与 HTTP 服务(Flutter 窗口与 headless 入口共用)。
|
||||
class Agent {
|
||||
Agent(this.options) : log = AgentLog();
|
||||
|
||||
final AgentOptions options;
|
||||
final AgentLog log;
|
||||
|
||||
late final PrintQueue queue;
|
||||
late final PrintBackend backend;
|
||||
late final AgentHttpServer server;
|
||||
int? port;
|
||||
|
||||
Future<int> start() async {
|
||||
final backendName = osBackendName();
|
||||
backend = options.mock ? MockBackend(onLog: log.write) : createOsBackend(onLog: log.write);
|
||||
queue = PrintQueue(backend, onLog: log.write);
|
||||
server = AgentHttpServer(
|
||||
queue: queue,
|
||||
backend: backend,
|
||||
mock: options.mock,
|
||||
manifestBackendName: backendName,
|
||||
);
|
||||
final ports = options.port == null ? const [38200, 38201, 38202] : <int>[options.port!];
|
||||
port = await server.start(candidatePorts: ports);
|
||||
log.write('饭卡打印助手已启动 http://127.0.0.1:$port'
|
||||
'(后端=$backendName,mock=${options.mock},agent=desktop-plugin)');
|
||||
return port!;
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
await server.stop();
|
||||
queue.dispose();
|
||||
log.dispose();
|
||||
}
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'agent.dart';
|
||||
import 'server/protocol.dart';
|
||||
|
||||
/// 饭卡打印助手主窗口(Phase 1 最小版:服务状态 + 打印机状态 + 运行日志;
|
||||
/// 托盘/首次引导/驱动安装在后续 Phase 增强)。
|
||||
Future<void> main(List<String> args) async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
final agent = Agent(AgentOptions.parse(args));
|
||||
String? startError;
|
||||
try {
|
||||
await agent.start();
|
||||
} catch (e) {
|
||||
startError = '$e';
|
||||
}
|
||||
runApp(DesktopPluginApp(agent: agent, startError: startError));
|
||||
}
|
||||
|
||||
class DesktopPluginApp extends StatelessWidget {
|
||||
const DesktopPluginApp({super.key, required this.agent, this.startError});
|
||||
|
||||
final Agent agent;
|
||||
final String? startError;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: '饭卡打印助手',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF0F6FDE)),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: AgentHomePage(agent: agent, startError: startError),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AgentHomePage extends StatefulWidget {
|
||||
const AgentHomePage({super.key, required this.agent, this.startError});
|
||||
|
||||
final Agent agent;
|
||||
final String? startError;
|
||||
|
||||
@override
|
||||
State<AgentHomePage> createState() => _AgentHomePageState();
|
||||
}
|
||||
|
||||
class _AgentHomePageState extends State<AgentHomePage> {
|
||||
PrinterStatus? _status;
|
||||
Object? _statusError;
|
||||
bool _loading = false;
|
||||
StreamSubscription<String>? _logSub;
|
||||
final _logs = <String>[];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_logSub = widget.agent.log.stream.listen((line) {
|
||||
if (mounted) setState(() => _logs.add(line));
|
||||
});
|
||||
_logs.addAll(widget.agent.log.lines);
|
||||
_refreshStatus();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_logSub?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _refreshStatus() async {
|
||||
setState(() => _loading = true);
|
||||
try {
|
||||
final status = await widget.agent.backend.getStatus();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_status = status;
|
||||
_statusError = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _statusError = '$e');
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final port = widget.agent.port;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('饭卡打印助手'),
|
||||
actions: [
|
||||
IconButton(icon: const Icon(Icons.refresh), tooltip: '刷新状态', onPressed: _refreshStatus),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
_serviceCard(port),
|
||||
const SizedBox(height: 12),
|
||||
_printerCard(),
|
||||
const SizedBox(height: 12),
|
||||
_logCard(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _serviceCard(int? port) {
|
||||
final err = widget.startError;
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
err == null && port != null ? Icons.check_circle : Icons.error,
|
||||
color: err == null && port != null ? Colors.green : Colors.red,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text('本机服务', style: Theme.of(context).textTheme.titleMedium),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(err ?? (port != null ? 'http://127.0.0.1:$port (管理端开卡页自动发现)' : '未启动')),
|
||||
const SizedBox(height: 4),
|
||||
Text('后端:${widget.agent.options.mock ? "mock(模拟)" : "系统打印队列"}'),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _printerCard() {
|
||||
final status = _status;
|
||||
final err = _statusError;
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
if (_loading)
|
||||
const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
else
|
||||
Icon(
|
||||
status != null && status.online ? Icons.print : Icons.print_disabled,
|
||||
color: status != null && status.online ? Colors.green : Colors.orange,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text('打印机', style: Theme.of(context).textTheme.titleMedium),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (err != null)
|
||||
Text('状态读取失败:$err', style: const TextStyle(color: Colors.red))
|
||||
else if (status != null) ...[
|
||||
Text('${status.model.isEmpty ? "未知型号" : status.model} · ${status.statusText}'),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'色带余量 ${status.ribbon.remain >= 0 ? "${status.ribbon.remain}%" : "未知"}'
|
||||
' · 剩卡 ${status.cardLeft >= 0 ? "${status.cardLeft} 张" : "未知"}',
|
||||
style: TextStyle(color: Theme.of(context).hintColor),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _logCard() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('运行日志', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
if (_logs.isEmpty)
|
||||
Text('(暂无)', style: TextStyle(color: Theme.of(context).hintColor))
|
||||
else
|
||||
...(_logs.length > 50 ? _logs.sublist(_logs.length - 50) : _logs)
|
||||
.map((line) => Text(line, style: const TextStyle(fontFamily: 'monospace', fontSize: 12))),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'dart:io';
|
||||
|
||||
import '../server/protocol.dart';
|
||||
import 'cups_backend.dart';
|
||||
|
||||
/// 打印后端抽象:Windows 走 HiTi PavoApi 直打(分层 BITMAP);macOS 走系统 CUPS 队列。
|
||||
abstract class PrintBackend {
|
||||
/// 后端名:pavo / cups / mock(暴露给日志)
|
||||
String get name;
|
||||
|
||||
Future<PrinterStatus> getStatus();
|
||||
|
||||
Future<void> printOneCard(PrintRequest request);
|
||||
}
|
||||
|
||||
/// manifest 里的后端名按操作系统报,与是否 mock 无关(对齐 C# 版行为)。
|
||||
String osBackendName() => Platform.isWindows ? 'pavo' : 'cups';
|
||||
|
||||
/// 创建当前操作系统的真实打印后端(非 mock)。
|
||||
PrintBackend createOsBackend({void Function(String line)? onLog}) {
|
||||
if (Platform.isWindows) {
|
||||
// Phase 3:PavoApi ffi 直打(待 Windows 实机联调)
|
||||
throw UnsupportedError('Windows PavoApi 后端尚未实现(Phase 3)');
|
||||
}
|
||||
return CupsPrintBackend(onLog: onLog);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import '../server/protocol.dart';
|
||||
import '../utils/command_runner.dart';
|
||||
import 'backend.dart';
|
||||
|
||||
/// 默认空日志(构造初始化列表里不能写 `(_) {}` 块体闭包,会被当成构造体花括号)。
|
||||
void noopLog(String line) {}
|
||||
|
||||
/// macOS 打印后端:HiTi 官方驱动(HiTiCardTypeMacDrivers pkg)安装后打印机成为系统
|
||||
/// CUPS 队列,直接把前端渲染好的 PNG 交给队列(lp 命令),驱动负责光栅化与色带分色。
|
||||
///
|
||||
/// 说明:CUPS 路径无树脂 K 层直控与色带余量读取,由驱动默认分色策略处理;
|
||||
/// 单面机(CS-200e)的背面按第二个独立作业顺序提交。
|
||||
class CupsPrintBackend implements PrintBackend {
|
||||
CupsPrintBackend({void Function(String line)? onLog}) : _log = onLog ?? noopLog;
|
||||
|
||||
final void Function(String line) _log;
|
||||
int _tempSeq = 0;
|
||||
|
||||
@override
|
||||
String get name => 'cups';
|
||||
|
||||
/// 打印队列信息(来自 lpoptions,字段纯 ASCII 不受系统语言本地化影响)。
|
||||
static const _noQueueHint =
|
||||
'未添加打印机:① 安装 HiTi Mac 驱动(HiTiCardTypeMacDrivers dmg 内的 pkg)→ ② USB 连接打印机 → ③ 系统设置→打印机与扫描仪 确认出现 HiTi 打印机后点刷新';
|
||||
|
||||
/// 发现打印队列。
|
||||
///
|
||||
/// macOS 会把 lpstat 输出本地化(中文系统"打印机xx正在接受请求"无空格粘连,LC_ALL=C 压不住),
|
||||
/// 因此首选 lpoptions:printer-uri-supported=ipp://localhost/printers/<队列名> 纯 ASCII;
|
||||
/// printer-state 为标准 IPP 状态(3 空闲 / 4 打印中 / 5 停止)。
|
||||
/// 兜底:lpstat -v 的中英双正则(用于(x)的设备 / device for (x):)。
|
||||
Future<List<_QueueInfo>> _discoverQueues() async {
|
||||
final result = <_QueueInfo>[];
|
||||
try {
|
||||
final lpopt = await runCommand('lpoptions', const [], tolerateExit: true);
|
||||
final uri = RegExp(r'printer-uri-supported=\S*/printers/(\S+)').firstMatch(lpopt);
|
||||
if (uri != null) {
|
||||
final name = uri.group(1)!;
|
||||
final state = RegExp(r'printer-state=(\d)').firstMatch(lpopt);
|
||||
final model = RegExp(r"printer-make-and-model='([^']*)'").firstMatch(lpopt);
|
||||
result.add(_QueueInfo(
|
||||
name,
|
||||
model?.group(1) ?? '',
|
||||
state != null ? int.parse(state.group(1)!) : 3,
|
||||
));
|
||||
}
|
||||
} on CommandException {
|
||||
// lpoptions 不可用时走 lpstat -v 兜底
|
||||
}
|
||||
if (result.isNotEmpty) {
|
||||
return result;
|
||||
}
|
||||
final vout = await runCommand('lpstat', const ['-v'], tolerateExit: true);
|
||||
for (final raw in vout.split('\n')) {
|
||||
final line = raw.trim();
|
||||
if (line.isEmpty) continue;
|
||||
// 英文 "device for NAME: ..." / 中文 "用于NAME的设备:..."
|
||||
final m = RegExp(r'device for (\S+):|用于(\S+)的设备').firstMatch(line);
|
||||
if (m != null) {
|
||||
final name = m.group(1) ?? m.group(2) ?? '';
|
||||
if (name.isNotEmpty && !result.any((q) => q.name == name)) {
|
||||
result.add(_QueueInfo(name, '', 3));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
_QueueInfo? _pickQueue(List<_QueueInfo> queues) {
|
||||
if (queues.isEmpty) return null;
|
||||
return queues.where((q) => q.name.toLowerCase().contains('hiti')).firstOrNull ??
|
||||
queues.where((q) => RegExp(r'CS[-_ ]?\d').hasMatch(q.name)).firstOrNull ??
|
||||
queues.first;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PrinterStatus> getStatus() async {
|
||||
try {
|
||||
final queue = _pickQueue(await _discoverQueues());
|
||||
if (queue == null) {
|
||||
return PrinterStatus.offline(_noQueueHint);
|
||||
}
|
||||
// IPP printer-state:3 空闲 / 4 打印中 / 5 停止
|
||||
final (status, statusText) = switch (queue.printerState) {
|
||||
4 => (0x00000002, '打印机正在打印'),
|
||||
5 => (0x00000080, '打印机已停止:请在 系统设置→打印机与扫描仪 里检查(缺纸/卡纸/暂停)'),
|
||||
_ => (0, '就绪'),
|
||||
};
|
||||
return PrinterStatus(
|
||||
online: queue.printerState != 5,
|
||||
model: queue.model.isEmpty ? queue.name : queue.model,
|
||||
connection: 'USB',
|
||||
ribbon: RibbonInfo(),
|
||||
status: status,
|
||||
statusText: statusText,
|
||||
);
|
||||
} catch (e) {
|
||||
return PrinterStatus.offline('状态读取失败:$e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> printOneCard(PrintRequest request) async {
|
||||
final queue = _pickQueue(await _discoverQueues());
|
||||
if (queue == null) {
|
||||
throw StateError('未找到系统打印队列,请先安装 HiTi Mac 驱动并添加打印机');
|
||||
}
|
||||
|
||||
final frontFile = await _writeTempPng(request.front!.color);
|
||||
String? backFile;
|
||||
try {
|
||||
final back = request.back;
|
||||
if (back != null && back.color.isNotEmpty) {
|
||||
backFile = await _writeTempPng(back.color);
|
||||
}
|
||||
final copies = request.copies < 1 ? 1 : request.copies;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
await runCommand('lp', ['-d', queue.name, frontFile]);
|
||||
if (backFile != null) {
|
||||
await runCommand('lp', ['-d', queue.name, backFile]);
|
||||
}
|
||||
}
|
||||
_log('已提交到 CUPS 队列 ${queue.name}(份数 $copies${backFile != null ? ',含背面' : ''})');
|
||||
} finally {
|
||||
await _deleteQuiet(frontFile);
|
||||
await _deleteQuiet(backFile);
|
||||
}
|
||||
}
|
||||
|
||||
/// data URL PNG 落临时文件供 lp 提交。
|
||||
Future<String> _writeTempPng(String dataUrl) async {
|
||||
final comma = dataUrl.indexOf(',');
|
||||
final base64Part = comma >= 0 ? dataUrl.substring(comma + 1) : dataUrl;
|
||||
final bytes = base64.decode(base64Part.replaceAll(RegExp(r'\s'), ''));
|
||||
final path =
|
||||
'${Directory.systemTemp.path}/card-${DateTime.now().microsecondsSinceEpoch}-${_tempSeq++}.png';
|
||||
await File(path).writeAsBytes(bytes);
|
||||
return path;
|
||||
}
|
||||
|
||||
Future<void> _deleteQuiet(String? path) async {
|
||||
if (path == null) return;
|
||||
try {
|
||||
await File(path).delete();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
class _QueueInfo {
|
||||
const _QueueInfo(this.name, this.model, this.printerState);
|
||||
|
||||
final String name;
|
||||
final String model;
|
||||
|
||||
/// IPP printer-state:3 空闲 / 4 打印中 / 5 停止
|
||||
final int printerState;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import '../server/protocol.dart';
|
||||
import 'backend.dart';
|
||||
import 'cups_backend.dart' show noopLog;
|
||||
|
||||
/// mock 后端:无打印机模拟全流程(打印 2.5 秒完成),供联调协议。
|
||||
class MockBackend implements PrintBackend {
|
||||
MockBackend({void Function(String line)? onLog}) : _log = onLog ?? noopLog;
|
||||
|
||||
final void Function(String line) _log;
|
||||
|
||||
@override
|
||||
String get name => 'mock';
|
||||
|
||||
@override
|
||||
Future<PrinterStatus> getStatus() async => PrinterStatus(
|
||||
online: true,
|
||||
model: 'HiTi CS-200e',
|
||||
firmware: 'v1.03',
|
||||
connection: 'USB',
|
||||
ribbon: RibbonInfo(type: 'YMCKO', remain: 63, remainCount: 63),
|
||||
cardLow: false,
|
||||
cardLeft: 87,
|
||||
status: 0,
|
||||
statusText: '就绪',
|
||||
);
|
||||
|
||||
@override
|
||||
Future<void> printOneCard(PrintRequest request) async {
|
||||
_log('[mock] 模拟打印任务(份数 ${request.copies})');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 2500));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:shelf/shelf_io.dart' as shelf_io;
|
||||
import 'package:shelf_router/shelf_router.dart';
|
||||
|
||||
import '../print/backend.dart';
|
||||
import 'print_queue.dart';
|
||||
import 'protocol.dart';
|
||||
|
||||
/// 协议 HTTP 服务:候选端口依次尝试绑定(与前端扫描约定一致:38200 起顺延两个)。
|
||||
class AgentHttpServer {
|
||||
AgentHttpServer({
|
||||
required this.queue,
|
||||
required this.backend,
|
||||
required this.mock,
|
||||
required this.manifestBackendName,
|
||||
this.agentName = 'desktop-plugin',
|
||||
});
|
||||
|
||||
final PrintQueue queue;
|
||||
|
||||
/// mock 模式下是 MockBackend,否则为系统对应后端
|
||||
final PrintBackend backend;
|
||||
final bool mock;
|
||||
|
||||
/// manifest 里的 backend 字段按操作系统报(pavo/cups),与是否 mock 无关(对齐 C# 版)
|
||||
final String manifestBackendName;
|
||||
final String agentName;
|
||||
|
||||
HttpServer? _server;
|
||||
int? _port;
|
||||
|
||||
int? get port => _port;
|
||||
|
||||
Future<int> start({List<int> candidatePorts = const [38200, 38201, 38202]}) async {
|
||||
final handler = const Pipeline().addMiddleware(_cors()).addHandler(_router.call);
|
||||
Object? lastError;
|
||||
for (final port in candidatePorts) {
|
||||
try {
|
||||
_server = await shelf_io.serve(
|
||||
handler,
|
||||
InternetAddress.loopbackIPv4,
|
||||
port,
|
||||
poweredByHeader: null,
|
||||
);
|
||||
_port = port;
|
||||
return port;
|
||||
} on SocketException catch (e) {
|
||||
lastError = e;
|
||||
}
|
||||
}
|
||||
throw StateError('端口 ${candidatePorts.first}-${candidatePorts.last} 均被占用,启动失败:$lastError');
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
await _server?.close(force: true);
|
||||
_server = null;
|
||||
_port = null;
|
||||
}
|
||||
|
||||
Router get _router {
|
||||
final router = Router()
|
||||
..get('/manifest', (Request r) => _ok({
|
||||
'plugins': [ManifestPlugin().toJson()],
|
||||
'agent': agentName,
|
||||
'backend': manifestBackendName,
|
||||
'mock': mock,
|
||||
}))
|
||||
..get('/api/card-printer/status', (Request r) async {
|
||||
try {
|
||||
return _ok((await backend.getStatus()).toJson());
|
||||
} catch (e) {
|
||||
return _ok(PrinterStatus.offline('状态读取失败:$e').toJson());
|
||||
}
|
||||
})
|
||||
..post('/api/card-printer/print', (Request r) async {
|
||||
try {
|
||||
final body = await r.readAsString();
|
||||
final Map<String, dynamic> json;
|
||||
try {
|
||||
json = jsonDecode(body) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
return _err('请求体不是合法 JSON');
|
||||
}
|
||||
final taskId = queue.submit(PrintRequest.fromJson(json));
|
||||
return _ok({'taskId': taskId});
|
||||
} catch (e) {
|
||||
return _err(PrintQueue.errorMessageOf(e));
|
||||
}
|
||||
})
|
||||
..get('/api/card-printer/task/<taskId>', (Request r, String taskId) {
|
||||
final task = queue.get(taskId);
|
||||
return task == null ? _err('任务不存在或已过期') : _ok(task.toJson());
|
||||
});
|
||||
return router;
|
||||
}
|
||||
|
||||
/// 助手只绑回环,CORS 放开 * 安全(含 OPTIONS 预检,供管理端 HTTPS 页面跨源访问)。
|
||||
Middleware _cors() {
|
||||
const headers = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Max-Age': '86400',
|
||||
};
|
||||
return (inner) => (Request req) async {
|
||||
if (req.method == 'OPTIONS') {
|
||||
return Response.ok('', headers: headers);
|
||||
}
|
||||
final res = await inner(req);
|
||||
return res.change(headers: headers);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Response _ok(Object? data) => Response.ok(
|
||||
jsonEncode({'code': 0, 'msg': 'ok', 'data': data}),
|
||||
headers: {'content-type': 'application/json; charset=utf-8'},
|
||||
);
|
||||
|
||||
Response _err(String msg) => Response.ok(
|
||||
jsonEncode({'code': 1, 'msg': msg, 'data': null}),
|
||||
headers: {'content-type': 'application/json; charset=utf-8'},
|
||||
);
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../print/backend.dart';
|
||||
import '../print/cups_backend.dart' show noopLog;
|
||||
import '../utils/command_runner.dart';
|
||||
import 'protocol.dart';
|
||||
|
||||
/// 打印队列中的单个任务运行时状态。
|
||||
class PrintQueueTask {
|
||||
PrintQueueTask({required this.taskId, required this.request});
|
||||
|
||||
final String taskId;
|
||||
final PrintRequest request;
|
||||
|
||||
/// printing / done / error
|
||||
String state = 'printing';
|
||||
int status = 0;
|
||||
String error = '';
|
||||
DateTime? finishedAt;
|
||||
}
|
||||
|
||||
/// 串行打印队列:打印机物理上一次只能打一张卡,任务逐个执行。
|
||||
///
|
||||
/// 任务状态存内存字典供前端轮询;完成后保留 30 分钟(对齐 C# 版 PrintQueue)。
|
||||
class PrintQueue {
|
||||
PrintQueue(this._backend, {void Function(String line)? onLog}) : _log = onLog ?? noopLog {
|
||||
_cleanupTimer = Timer.periodic(const Duration(minutes: 5), (_) => _cleanupOld());
|
||||
}
|
||||
|
||||
final PrintBackend _backend;
|
||||
final void Function(String line) _log;
|
||||
|
||||
final _tasks = <String, PrintQueueTask>{};
|
||||
Future<void> _tail = Future.value();
|
||||
Timer? _cleanupTimer;
|
||||
int _seq = 0;
|
||||
|
||||
/// 提交打印任务,立即返回 taskId。
|
||||
String submit(PrintRequest request) {
|
||||
if (request.front == null || request.front!.color.isEmpty) {
|
||||
throw ArgumentError('缺少正面卡面图(front.color)');
|
||||
}
|
||||
final task = PrintQueueTask(taskId: 't${++_seq}', request: request);
|
||||
_tasks[task.taskId] = task;
|
||||
// 串行链:每个任务等前一个完成后执行,异常在 _run 内消化,链条不中断
|
||||
_tail = _tail.then((_) => _run(task));
|
||||
return task.taskId;
|
||||
}
|
||||
|
||||
PrintTaskDto? get(String taskId) {
|
||||
final task = _tasks[taskId];
|
||||
if (task == null) return null;
|
||||
return PrintTaskDto(taskId: task.taskId, state: task.state, status: task.status, statusText: task.error);
|
||||
}
|
||||
|
||||
Future<void> _run(PrintQueueTask task) async {
|
||||
_log('[${task.taskId}] 开始打印(份数 ${task.request.copies})');
|
||||
try {
|
||||
await _backend.printOneCard(task.request);
|
||||
task.state = 'done';
|
||||
_log('[${task.taskId}] 打印完成');
|
||||
} catch (e) {
|
||||
task.state = 'error';
|
||||
task.error = errorMessageOf(e);
|
||||
_log('[${task.taskId}] 打印失败:${task.error}');
|
||||
} finally {
|
||||
task.finishedAt = DateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
/// 清掉已完成/失败超 30 分钟的任务,避免内存常驻增长。
|
||||
void _cleanupOld() {
|
||||
final now = DateTime.now();
|
||||
_tasks.removeWhere((_, task) =>
|
||||
task.finishedAt != null && now.difference(task.finishedAt!).inMinutes > 30);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_cleanupTimer?.cancel();
|
||||
_cleanupTimer = null;
|
||||
}
|
||||
|
||||
/// 从任意异常里提取可读文案(前端 statusText 直接展示)。
|
||||
static String errorMessageOf(Object e) {
|
||||
if (e is CommandException) return e.message;
|
||||
try {
|
||||
final dynamic err = e;
|
||||
final msg = err.message;
|
||||
if (msg is String && msg.isNotEmpty) return msg;
|
||||
} catch (_) {}
|
||||
return e.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/// 与前端 `biz-pc-cloud-zax/src/api/plugin/cardPrinter.ts` 约定的协议 DTO。
|
||||
///
|
||||
/// 字段序列化一律 camelCase,响应统一信封 `{code, msg, data}`(code=0 成功),
|
||||
/// 与 C# 版 card-printer-agent 的 ApiModels.cs 逐字段对齐。
|
||||
library;
|
||||
|
||||
class ManifestPlugin {
|
||||
ManifestPlugin({this.id = 'card-printer', this.name = '卡片打印机', this.version = '1.0.0'});
|
||||
|
||||
final String id;
|
||||
final String name;
|
||||
final String version;
|
||||
|
||||
Map<String, dynamic> toJson() => {'id': id, 'name': name, 'version': version};
|
||||
}
|
||||
|
||||
class RibbonInfo {
|
||||
RibbonInfo({this.type = '', this.remain = -1, this.remainCount = -1});
|
||||
|
||||
/// 色带类型名(如 YMCKO),未知空串
|
||||
String type;
|
||||
|
||||
/// 色带余量百分比 0~100,未知 -1(按常见 100 张装色带折算)
|
||||
int remain;
|
||||
|
||||
/// 色带剩余张数(设备原始值),未知 -1
|
||||
int remainCount;
|
||||
|
||||
Map<String, dynamic> toJson() => {'type': type, 'remain': remain, 'remainCount': remainCount};
|
||||
}
|
||||
|
||||
/// GET /api/card-printer/status 响应
|
||||
class PrinterStatus {
|
||||
PrinterStatus({
|
||||
this.online = false,
|
||||
this.model = '',
|
||||
this.firmware = '',
|
||||
this.connection = 'USB',
|
||||
RibbonInfo? ribbon,
|
||||
this.cardLow = false,
|
||||
this.cardLeft = -1,
|
||||
this.status = 0,
|
||||
this.statusText = '',
|
||||
}) : ribbon = ribbon ?? RibbonInfo();
|
||||
|
||||
bool online;
|
||||
String model;
|
||||
String firmware;
|
||||
|
||||
/// USB / IP
|
||||
String connection;
|
||||
RibbonInfo ribbon;
|
||||
|
||||
/// 卡量是否不足
|
||||
bool cardLow;
|
||||
|
||||
/// 剩余卡量(张),未知 -1
|
||||
int cardLeft;
|
||||
|
||||
/// HiTi 设备状态码,0 = 就绪
|
||||
int status;
|
||||
String statusText;
|
||||
|
||||
/// 打印机已断开/未连接的通用离线态
|
||||
factory PrinterStatus.offline(String statusText) => PrinterStatus(
|
||||
online: false,
|
||||
status: 0x00000080,
|
||||
statusText: statusText,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'online': online,
|
||||
'model': model,
|
||||
'firmware': firmware,
|
||||
'connection': connection,
|
||||
'ribbon': ribbon.toJson(),
|
||||
'cardLow': cardLow,
|
||||
'cardLeft': cardLeft,
|
||||
'status': status,
|
||||
'statusText': statusText,
|
||||
};
|
||||
}
|
||||
|
||||
/// 单面打印图:color 必传,k 为可选树脂黑文字层
|
||||
class CardSideImage {
|
||||
CardSideImage({required this.color, this.k});
|
||||
|
||||
/// 1014×642 彩色层 PNG data URL
|
||||
final String color;
|
||||
|
||||
/// 8bit 灰度树脂 K 文字层 PNG data URL,白底黑字
|
||||
final String? k;
|
||||
|
||||
factory CardSideImage.fromJson(Map<String, dynamic> json) => CardSideImage(
|
||||
color: json['color'] as String? ?? '',
|
||||
k: json['k'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
/// POST /api/card-printer/print 请求
|
||||
class PrintRequest {
|
||||
PrintRequest({this.copies = 1, this.front, this.back});
|
||||
|
||||
final int copies;
|
||||
final CardSideImage? front;
|
||||
final CardSideImage? back;
|
||||
|
||||
factory PrintRequest.fromJson(Map<String, dynamic> json) {
|
||||
CardSideImage? side(Object? raw) =>
|
||||
raw is Map<String, dynamic> ? CardSideImage.fromJson(raw) : null;
|
||||
return PrintRequest(
|
||||
copies: (json['copies'] as num?)?.toInt() ?? 1,
|
||||
front: side(json['front']),
|
||||
back: side(json['back']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/card-printer/task/{taskId} 响应
|
||||
class PrintTaskDto {
|
||||
PrintTaskDto({required this.taskId, this.state = 'printing', this.status = 0, this.statusText = ''});
|
||||
|
||||
final String taskId;
|
||||
|
||||
/// printing / done / error
|
||||
final String state;
|
||||
final int status;
|
||||
|
||||
/// error 态时携带错误文案
|
||||
final String statusText;
|
||||
|
||||
Map<String, dynamic> toJson() =>
|
||||
{'taskId': taskId, 'state': state, 'status': status, 'statusText': statusText};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// 外部命令执行失败(非零退出/超时/无法启动)。
|
||||
class CommandException implements Exception {
|
||||
CommandException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 运行外部命令(lp/lpoptions/lpstat)并返回标准输出。
|
||||
///
|
||||
/// 一律用参数列表传参不经过 shell,杜绝命令注入;
|
||||
/// 强制 LC_ALL=C 英文输出(macOS 会把 lpstat/lp 本地化,中文系统队列名与状态词粘连无法按空格解析)。
|
||||
Future<String> runCommand(
|
||||
String executable,
|
||||
List<String> arguments, {
|
||||
int timeoutMs = 15000,
|
||||
bool tolerateExit = false,
|
||||
}) async {
|
||||
final Process process;
|
||||
try {
|
||||
process = await Process.start(
|
||||
executable,
|
||||
arguments,
|
||||
environment: const {'LC_ALL': 'C', 'LANG': 'C'},
|
||||
);
|
||||
} on ProcessException catch (e) {
|
||||
throw CommandException('无法启动 $executable:${e.message}');
|
||||
}
|
||||
|
||||
// stdout/stderr 立即挂上消费 Future,避免管道缓冲区写满导致死锁
|
||||
final stdoutFuture = process.stdout.transform(utf8.decoder).join();
|
||||
final stderrFuture = process.stderr.transform(utf8.decoder).join();
|
||||
|
||||
final int exitCode;
|
||||
try {
|
||||
exitCode = await process.exitCode.timeout(Duration(milliseconds: timeoutMs));
|
||||
} on TimeoutException {
|
||||
process.kill();
|
||||
throw CommandException('$executable 执行超时');
|
||||
}
|
||||
|
||||
final out = await stdoutFuture;
|
||||
if (exitCode != 0 && !tolerateExit) {
|
||||
final err = await stderrFuture;
|
||||
throw CommandException('$executable 返回 $exitCode:${err.trim()}');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Reference in new issue
Block a user