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,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};
|
||||
}
|
||||
Reference in new issue
Block a user