#include "backendlink.h" #include "appconfig.h" #include "localplans.h" #include "uiformat.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { const int kStationCount = 4; const int kReconnectMs = 1500; // 断线 1.5s 单次触发重连(配合状态检查防止重连风暴) const int kDisconnectDebounceMs = 2500; // 闪断 2.5s 内自动恢复时不向主界面刷断线闪烁 const int kConnectTimeoutMs = 10000; // 建立连接超过 10s 无响应 → 主动断开 const int kSilenceTimeoutMs = 20000; // 已连接但 20s 没有任何后端消息 → 主动断开 const int kCommandPollMs = 2000; // 未结束命令的查询间隔 // 命令刚发出去时后端还没落记录,此时 GetCommand 会回 NOT_FOUND。 // 这两个宽限值决定「暂时查不到」要忍多久,别把还在途的命令当场判死。 const qint64 kPollGraceMs = 3000; // 发出后这么久内不轮询 const qint64 kRegisterGraceMs = 8000; // 这么久内的 NOT_FOUND 视为「还没到」,继续跟踪 const int kUartMuteMs = 5000; // 点开始测试后丢弃旧会话尾巴的时间窗(到期强制恢复,防止永久静音) const int kBackfillPages = 8; // 连接后回填历史 UART 的页数上限(8 × 64 KB) const int kBackfillPageBytes = 65536; // ReadBiosUart 单页字节数(接口上限) const int kBackfillHoldMs = 10000; // 回填期间压住推送包的最长时间(超时强制放行,防止永久压包) QString stationId(int index) // 界面工位 0..3 → S1..S4 { return QStringLiteral("S%1").arg(index + 1); } int stationIndex(const QString &id) // S1..S4 → 0..3,未知返回 -1 { if (id.size() != 2 || !id.startsWith(QLatin1Char('S'))) return -1; const int n = id.at(1).digitValue(); return (n >= 1 && n <= kStationCount) ? n - 1 : -1; } qint64 nowMs() { return QDateTime::currentMSecsSinceEpoch(); } // stage_errors 里每一项转成一句人能读的话,并提取原始 message 作为续行合并键。 QString describeStageError(const QJsonValue &value, QString *rawKeyOut = nullptr) { if (rawKeyOut) rawKeyOut->clear(); if (value.isString()) { const QString s = value.toString().trimmed(); if (rawKeyOut) *rawKeyOut = s; return s; } if (value.isBool()) return value.toBool() ? QStringLiteral("true") : QStringLiteral("false"); if (value.isDouble()) return QString::number(value.toDouble()); if (value.isObject()) { const QJsonObject obj = value.toObject(); const QString msg = obj.value(QStringLiteral("message")).toString().trimmed(); if (rawKeyOut) *rawKeyOut = msg; QStringList meta; const QJsonValue cpuVal = obj.value(QStringLiteral("cpu")); const QJsonValue chVal = obj.value(QStringLiteral("channel")); bool hasCpu = false; int cpuIdx = -1; if (cpuVal.isDouble()) { cpuIdx = cpuVal.toInt(-1); hasCpu = (cpuIdx >= 0 && cpuIdx <= 1); } else if (cpuVal.isString()) { bool ok = false; const int v = cpuVal.toString().trimmed().toInt(&ok); if (ok && v >= 0 && v <= 1) { cpuIdx = v; hasCpu = true; } } QString chRaw = chVal.isString() ? chVal.toString().trimmed() : (chVal.isDouble() ? QString::number(chVal.toInt(-1)) : QString()); int chIdx = -1; if (!chRaw.isEmpty()) { bool ok = false; const int v = chRaw.toInt(&ok); if (ok && v >= 0 && v < 12) chIdx = v; } if (hasCpu && chIdx >= 0) { const QChar letter = QLatin1Char('A' + chIdx); meta << QStringLiteral("CPU%1_CH%2 (CH%3)").arg(cpuIdx).arg(letter).arg(chIdx); } else if (hasCpu) { meta << QStringLiteral("CPU%1").arg(cpuIdx); } else if (!chRaw.isEmpty()) { meta << QStringLiteral("CH%1").arg(chRaw); } const QJsonValue dimmVal = obj.value(QStringLiteral("dimm")); if (dimmVal.isDouble() && dimmVal.toInt(-1) >= 0) meta << QStringLiteral("DIMM%1").arg(dimmVal.toInt()); const QJsonValue rankVal = obj.value(QStringLiteral("rank")); if (rankVal.isDouble() && rankVal.toInt(-1) >= 0) meta << QStringLiteral("Rank%1").arg(rankVal.toInt()); const QJsonValue bankVal = obj.value(QStringLiteral("bank")); if (bankVal.isDouble() && bankVal.toInt(-1) >= 0) meta << QStringLiteral("Bank%1").arg(bankVal.toInt()); const QString addr = obj.value(QStringLiteral("address")).toString().trimmed(); if (!addr.isEmpty()) meta << QStringLiteral("Addr=%1").arg(addr); const QString kind = obj.value(QStringLiteral("kind")).toString().trimmed(); QString head = meta.join(QStringLiteral(" · ")); if (head.isEmpty() && !kind.isEmpty() && msg.isEmpty()) head = kind; if (!head.isEmpty() && !msg.isEmpty()) return QStringLiteral("[%1] %2").arg(head, msg); if (!msg.isEmpty()) return msg; if (!head.isEmpty()) return head; return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact)); } if (value.isArray()) return QString::fromUtf8(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); return QString(); } // X-Client-Id 的落地文件:跟 qt-plans.json / config.json 放同一个目录 QString clientIdPath() { return QDir(appWritableDir()).filePath(QStringLiteral("client-id.txt")); } // 读上次用的客户端标识,没有就生成一个并写盘 QString loadOrCreateClientId() { const QString path = clientIdPath(); QFile in(path); if (in.open(QIODevice::ReadOnly)) { const QString saved = QString::fromUtf8(in.readAll()).trimmed(); in.close(); if (!saved.isEmpty()) return saved; } const QString id = QStringLiteral("qt-%1").arg( QUuid::createUuid().toString(QUuid::WithoutBraces).left(8)); QSaveFile out(path); if (out.open(QIODevice::WriteOnly)) { out.write(id.toUtf8()); out.commit(); } qInfo().noquote() << "[backend] 生成新的客户端标识" << id << "→" << path; return id; } } // namespace BackendLink::BackendLink(QObject *parent) : QObject(parent) { // command_id 必须全局唯一:同一后端会记住历史命令,重启后自增序号会撞上旧编号, // 后端会回 ALREADY_EXISTS(同编号参数不同)。这里加一个进程级时间戳后缀。 m_idToken = QStringLiteral("%1").arg(QDateTime::currentMSecsSinceEpoch() % 100000000); // 手册 7.2:握手带 X-Client-Id,重连时仍算同一个客户端,测试期间不会被别的连接抢走 // 工位控制权。这里把标识落盘:上位机重启后仍报同一个 id,后端才认「还是这台机器」。 // 否则每次启动都是「另一客户端」,正在跑的工位连 StartTest 都发不进去 // (FAILED_PRECONDITION 当前工位正由另一客户端执行测试)。 m_clientId = loadOrCreateClientId(); connect(&m_ws, &QWebSocket::connected, this, &BackendLink::onConnected); connect(&m_ws, &QWebSocket::disconnected, this, &BackendLink::onDisconnected); connect(&m_ws, &QWebSocket::textMessageReceived, this, &BackendLink::onTextMessage); #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) connect(&m_ws, &QWebSocket::errorOccurred, #else connect(&m_ws, QOverload::of(&QWebSocket::error), #endif this, [this](QAbstractSocket::SocketError) { const QString err = m_ws.errorString(); qInfo().noquote() << "[backend]" << err; if (err.contains(QStringLiteral("proxy"), Qt::CaseInsensitive)) qInfo().noquote() << "[backend] 提示:连接受本机代理影响;内网后端已强制直连," "若仍失败请核对 config.json 的 url 与系统代理设置"; }); m_reconnect.setSingleShot(true); m_reconnect.setInterval(kReconnectMs); connect(&m_reconnect, &QTimer::timeout, this, &BackendLink::openSocket); m_disconnectDebounce.setSingleShot(true); m_disconnectDebounce.setInterval(kDisconnectDebounceMs); connect(&m_disconnectDebounce, &QTimer::timeout, this, [this]() { if (!isConnected() && m_reportedConnected) { m_reportedConnected = false; emit connectionChanged(false); } }); m_health.setInterval(1000); connect(&m_health, &QTimer::timeout, this, &BackendLink::onHealthTick); m_health.start(); m_commandPoll.setInterval(kCommandPollMs); connect(&m_commandPoll, &QTimer::timeout, this, &BackendLink::pollPending); m_commandPoll.start(); } BackendLink::~BackendLink() { // QWebSocket 析构时会补发一次 disconnected。那时本对象的成员(定时器、处理器表) // 正在/已经析构,onDisconnected 里再 start() 定时器就是野指针;而它 emit 出去的 // connectionChanged 还会去摸主窗口已经删掉的控件 —— 关窗必崩(实测 SIGSEGV)。 // 先把 socket 的信号摘干净,让析构静默进行。 m_health.stop(); m_reconnect.stop(); m_disconnectDebounce.stop(); m_commandPoll.stop(); m_ws.disconnect(this); } void BackendLink::start() { // 纯净接口地址:默认按新联想一体控制主机 192.168.2.68(BMC + PXE 同机一体部署); // config.json 里加 "backend": {"url": "ws://..."} 可覆盖(本地后端就写 127.0.0.1) m_url = QStringLiteral("ws://192.168.2.68:8080/ws?view=qt-clean"); const QString path = appConfigPath(QStringLiteral("config.json")); QFile f(path); if (f.open(QIODevice::ReadOnly)) { const QJsonObject root = QJsonDocument::fromJson(f.readAll()).object(); const QString u = root.value(QStringLiteral("backend")).toObject() .value(QStringLiteral("url")).toString(); if (!u.isEmpty()) m_url = u; } // 兜底:漏了 view=qt-clean 就会连到全量接口(那套没有 StartTest,会报 UNIMPLEMENTED) if (!m_url.contains(QStringLiteral("view="))) { m_url += m_url.contains(QLatin1Char('?')) ? QStringLiteral("&view=qt-clean") : QStringLiteral("?view=qt-clean"); qInfo().noquote() << "[backend] 地址未指定 view,已自动补成" << m_url; } openSocket(); } void BackendLink::openSocket() { if (m_ws.state() != QAbstractSocket::UnconnectedState) return; qInfo().noquote() << "[backend] 连接" << m_url << "..."; m_connectStartMs = nowMs(); // 内网 / 本机后端一律直连,不让 QWebSocket 去用系统或环境变量代理。 // 开发机上常设 http_proxy(本机抓包/加速代理),Qt 会把它拿去连 ws://, // 握手前就报 "The proxy type is invalid for this operation",于是每 3s 重连、 // 界面一直「控制台离线」,点开始测试就提示「后端未连接,本次未下发任务」。 // 后端在局域网,本来也不该经过代理;外网地址仍沿用系统默认代理。 const QUrl url(m_url); const QString host = url.host(); const bool direct = host.isEmpty() || host == QStringLiteral("localhost") || host == QStringLiteral("127.0.0.1") || host == QLatin1String("::1") || host.startsWith(QStringLiteral("192.168.")) || host.startsWith(QStringLiteral("10.")) || host.startsWith(QStringLiteral("172.")); m_ws.setProxy(direct ? QNetworkProxy(QNetworkProxy::NoProxy) : QNetworkProxy(QNetworkProxy::DefaultProxy)); QNetworkRequest request{QUrl(m_url)}; request.setRawHeader("X-Client-Id", m_clientId.toUtf8()); m_ws.open(request); } void BackendLink::onConnected() { qInfo().noquote() << "[backend] 已连上" << m_url << "client_id =" << m_clientId; m_lastMessageMs = nowMs(); // 断线后不自动恢复阶段动作:手册要求连接变化时暂停本地自动下发。 // 只有用户明确发起新一轮 StartTest 才解除暂停,避免重连后对旧 input_id 误操作。 m_reconnect.stop(); m_disconnectDebounce.stop(); if (!m_reportedConnected) { m_reportedConnected = true; emit connectionChanged(true); } sendRequest(QStringLiteral("GetSystemInfo"), {}, [this](const QJsonObject &result) { const QString version = result.value(QStringLiteral("version")).toString(); const QString mode = result.value(QStringLiteral("mode")).toString(); qInfo().noquote() << "[backend] 后端版本" << version << "mode" << mode; const QString hint = (mode == QStringLiteral("simulated")) ? QStringLiteral("(模拟模式,不能作为实机验收证据)") : QString(); emit logLine(0, QStringLiteral("[backend] 已连接后端 %1 版本 %2 %3%4") .arg(m_url, version, mode, hint)); }); // 把各工位当前 UART 会话的历史字节补回来:后端只在「有新字节」时推, // 程序刚起来那一刻 BIOS 往往已经没有输出,只等推送会一个字都看不到。 // 走过的字节由 applyBiosUart 里的 session + offset 游标去重,不会重复显示。 for (int i = 0; i < kStationCount; ++i) backfillBiosUart(i, 0, kBackfillPages); } void BackendLink::backfillBiosUart(int station, quint64 offset, int pagesLeft) { if (station < 0 || station >= kStationCount || pagesLeft <= 0) return; QJsonObject params; params.insert(QStringLiteral("station_id"), stationId(station)); params.insert(QStringLiteral("offset"), QString::number(offset)); params.insert(QStringLiteral("max_bytes"), kBackfillPageBytes); // 开链(offset 0)时打开压包窗口:这段时间的推送先进 m_uartDeferred,等历史补齐再放 if (offset == 0) m_backfillHoldUntil[station] = nowMs() + kBackfillHoldMs; sendRequest(QStringLiteral("ReadBiosUart"), params, [this, station, offset, pagesLeft](const QJsonObject &result) { const quint64 next = result.value(QStringLiteral("next_offset")).toVariant().toULongLong(); const bool hasMore = result.value(QStringLiteral("has_more")).toBool(); // 和推送走同一条路:会话比对、缺口处理、按行切分、去重全在这里 applyBiosUart(result); if (!hasMore) { m_backfillHoldUntil[station] = 0; flushDeferredUart(station); return; } if (next <= offset) { // 后端没前进,别死循环 qInfo().noquote() << "[backend]" << stationId(station) << "UART 回填偏移未前进,停止本轮回填"; m_backfillHoldUntil[station] = 0; flushDeferredUart(station); return; } if (pagesLeft <= 1) { qInfo().noquote() << "[backend]" << stationId(station) << "UART 回填达到本次上限(" << kBackfillPages * kBackfillPageBytes / 1024 << "KB),余下部分随后端推送继续显示"; m_backfillHoldUntil[station] = 0; flushDeferredUart(station); return; } backfillBiosUart(station, next, pagesLeft - 1); }); } void BackendLink::flushDeferredUart(int station) { if (station < 0 || station >= kStationCount || m_uartDeferred[station].isEmpty()) return; const QVector queued = m_uartDeferred[station]; m_uartDeferred[station].clear(); qInfo().noquote() << "[backend]" << stationId(station) << "UART 回填完成,补处理回填期间积压的" << queued.size() << "个推送包"; for (const QJsonObject &packet : queued) applyBiosUart(packet); } void BackendLink::onDisconnected() { qInfo().noquote() << "[backend] 连接断开," << QString::number(kReconnectMs / 1000.0, 'f', 1) << "s 后重试"; m_autoPaused = true; // 连接变化 → 暂停自动下发 m_handlers.clear(); m_errorHandlers.clear(); // 旧的推送包属于上一条连接:重连后后端会重放当前会话,回填也会重新走,这里直接丢掉 for (int i = 0; i < kStationCount; ++i) { m_backfillHoldUntil[i] = 0; m_uartDeferred[i].clear(); // 在途 SetStageIntent 的回执可能随断线丢失,不能让 pending 永久卡住; // ready 也不能在重连后被当成当前轮次已可靠预置。 m_stageIntentPending[i].clear(); m_stageIntentReady[i].clear(); m_startRpcInFlight[i] = false; if (!m_fileQueryCmd[i].isEmpty()) { const QString failedCmd = m_fileQueryCmd[i]; m_fileQueryCmd[i].clear(); forgetCommand(failedCmd); emit uefiFilesArrived(i, false, m_fileQueryPath[i], QStringList(), QStringLiteral("后端连接已断开,请重试")); } } if (m_reportedConnected && !m_disconnectDebounce.isActive()) m_disconnectDebounce.start(); if (!m_reconnect.isActive()) m_reconnect.start(); } void BackendLink::onHealthTick() { const qint64 now = nowMs(); // 回填超时兜底:ReadBiosUart 没回来(后端不支持 / 丢包)也不能把推送永久压着 for (int i = 0; i < kStationCount; ++i) { if (m_backfillHoldUntil[i] != 0 && now >= m_backfillHoldUntil[i]) { m_backfillHoldUntil[i] = 0; if (!m_uartDeferred[i].isEmpty()) { qInfo().noquote() << "[backend]" << stationId(i) << "UART 回填超时,先放行积压的" << m_uartDeferred[i].size() << "个推送包"; flushDeferredUart(i); } } } if (m_ws.state() == QAbstractSocket::ConnectingState) { if (m_connectStartMs > 0 && now - m_connectStartMs > kConnectTimeoutMs) { qInfo().noquote() << "[backend] 连接超时," << kConnectTimeoutMs / 1000 << "s 内无响应,主动断开"; m_ws.abort(); } return; } if (isConnected() && m_lastMessageMs > 0 && now - m_lastMessageMs > kSilenceTimeoutMs) { qInfo().noquote() << "[backend] 连续" << kSilenceTimeoutMs / 1000 << "s 没有任何后端消息,主动断开重连"; m_ws.abort(); } } void BackendLink::sendRequest(const QString &method, const QJsonObject ¶ms, const std::function &onOk, const std::function &onError) { if (!isConnected()) { qInfo().noquote() << "[backend] 未连接,丢弃" << method; // 没连上也算失败:不能把调用方晾在那儿等回音 if (onError) onError(QStringLiteral("OFFLINE"), QStringLiteral("未连接后端")); return; } const QString id = QStringLiteral("qt-%1").arg(++m_idCounter); if (onOk) m_handlers.insert(id, onOk); if (onError) m_errorHandlers.insert(id, onError); QJsonObject frame; frame.insert(QStringLiteral("v"), 1); frame.insert(QStringLiteral("id"), id); frame.insert(QStringLiteral("method"), method); frame.insert(QStringLiteral("params"), params); m_ws.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact))); } void BackendLink::onTextMessage(const QString &json) { m_lastMessageMs = nowMs(); const QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); if (obj.isEmpty()) return; // 推送(没有 id,先按 event 分流) const QString event = obj.value(QStringLiteral("event")).toString(); if (!event.isEmpty()) { const QJsonObject result = obj.value(QStringLiteral("result")).toObject(); if (event == QStringLiteral("state")) { applyState(result); } else if (event == QStringLiteral("bios_uart")) { // 回填期间先把推送压住:等 ReadBiosUart 把历史补齐再按原顺序放, // 否则推送把游标先推到很后面,回填回来的前几万字节会被当成重复整包丢掉。 const int index = stationIndex(result.value(QStringLiteral("station_id")).toString()); if (index >= 0 && m_backfillHoldUntil[index] > nowMs()) m_uartDeferred[index].append(result); else applyBiosUart(result); } else if (event == QStringLiteral("task_complete")) { // 0.8.1.19:每轮终态主动推送。只接受当前 boot_id 的事件,避免旧轮次迟到包推进新任务。 const int index = stationIndex(result.value(QStringLiteral("station_id")).toString()); const QString bootId = result.value(QStringLiteral("boot_id")).toString(); const QString taskStatus = result.value(QStringLiteral("task_status")).toString(); const bool complete = result.value(QStringLiteral("complete")).toBool(); const bool terminal = taskStatus == QStringLiteral("completed") || taskStatus == QStringLiteral("failed"); if (index >= 0 && complete && terminal) { const bool eventIsOld = !m_waitingNewBoot[index] && !bootId.isEmpty() && !m_bootId[index].isEmpty() && bootId != m_bootId[index]; const bool stillOldDuringRestart = m_waitingNewBoot[index] && (bootId.isEmpty() || bootId == m_bootId[index]); if (eventIsOld || stillOldDuringRestart) { qInfo().noquote() << "[backend] 忽略旧轮次 task_complete:" << stationId(index) << bootId << "当前 boot_id =" << m_bootId[index]; } else { // 新轮次的 task_complete 可能先于下一帧 state 到达;boot_id 不同且正等待新轮次时, // 以该事件确认轮次切换,避免误丢真正的终态通知。 if (!bootId.isEmpty() && m_waitingNewBoot[index] && bootId != m_bootId[index]) { m_bootId[index] = bootId; m_waitingNewBoot[index] = false; m_appliedCpu[index].clear(); m_handledInput[index].clear(); m_stageDoneKeys[index].clear(); m_stagePendingCmd[index].clear(); m_stagePendingKey[index].clear(); m_stationPaused[index] = false; m_blockedWarned[index] = false; m_lastCompleteCmd[index].clear(); m_lastTaskStatus[index].clear(); m_stageErrorsJson[index].clear(); m_lastVerdict[index].clear(); } // 后端多 Profile 批次中间单轮完成(batch_complete=false 且未失败): // 只推快照和日志,不推进本地队列终态也不触发降温收尾。 const QString verdict = result.value(QStringLiteral("verdict")).toString(); const bool batchIntermediate = result.contains(QStringLiteral("batch_complete")) && !result.value(QStringLiteral("batch_complete")).toBool(true) && taskStatus != QStringLiteral("failed") && verdict != QStringLiteral("fail"); // 快照事件与「队列推进」分开去重: // StageAction/GetCommand 的 complete=true 可能先到并占用 // m_lastTaskCompleteBoot;不能因此吞掉后到的 verdict/stage_completions。 const bool newSnapshot = bootId.isEmpty() || bootId != m_lastTaskCompleteEventBoot[index]; if (newSnapshot) { if (!bootId.isEmpty() && !batchIntermediate) m_lastTaskCompleteEventBoot[index] = bootId; emit taskCompleteArrived(index, result); } // 队列终态单独去重,命令回执先到时事件只补快照、不重复推进。 if (!batchIntermediate && (bootId.isEmpty() || bootId != m_lastTaskCompleteBoot[index])) { if (!bootId.isEmpty()) m_lastTaskCompleteBoot[index] = bootId; m_lastTaskStatus[index] = taskStatus; emit taskProgressReported(index, true, taskStatus); } } } } return; } // 响应(按 id 匹配) const QString id = obj.value(QStringLiteral("id")).toString(); const auto it = m_handlers.constFind(id); const auto itErr = m_errorHandlers.constFind(id); if (it == m_handlers.constEnd() && itErr == m_errorHandlers.constEnd()) return; std::function handler; if (it != m_handlers.constEnd()) { handler = it.value(); m_handlers.erase(it); } std::function errorHandler; if (itErr != m_errorHandlers.constEnd()) { errorHandler = itErr.value(); m_errorHandlers.erase(itErr); } if (obj.value(QStringLiteral("ok")).toBool()) { if (handler) handler(obj.value(QStringLiteral("result")).toObject()); return; } const QJsonObject err = obj.value(QStringLiteral("error")).toObject(); const QString code = err.value(QStringLiteral("code")).toString(); const QString message = err.value(QStringLiteral("message")).toString(); qInfo().noquote() << "[backend] 请求" << id << "失败:" << code << message; if (code == QStringLiteral("UNIMPLEMENTED")) { // 常见原因:连到了全量 /ws(无 view=qt-clean)或后端版本低于 0.8.1.2 qInfo().noquote() << "[backend] 提示:后端不支持该方法,请确认地址带 ?view=qt-clean," "且后端为 0.8.1.2 及以上版本"; } if (errorHandler) errorHandler(code, message); } // --------------------------------------------------------------------------- // 状态推送:四工位快照 → 落库 + 本地 plan // --------------------------------------------------------------------------- // 手册 9.2:StartTest / StageAction / GetCommand 的命令结果对象新增 // complete(当前任务是否到终态)与 task_status(任务状态枚举)。 // complete 也可能表示「这条命令自己到终态」,所以上层只有同时看到 // task_status=completed/failed 才把它当作任务终态,避免阶段动作提前推进队列。 void BackendLink::reportCommandProgress(int station, const QString &commandId, const QJsonObject &result) { if (station < 0 || station >= kStationCount) return; // 字段可能在命令结果顶层,也可能嵌在 result.result 里(GetCommand 把业务结果 // 放在嵌套 result 下),两处都认,兼容后端不同实现。 bool complete = result.value(QStringLiteral("complete")).toBool(); QString taskStatus = result.value(QStringLiteral("task_status")).toString(); const QJsonObject inner = result.value(QStringLiteral("result")).toObject(); if (!complete) complete = inner.value(QStringLiteral("complete")).toBool(); if (taskStatus.isEmpty()) taskStatus = inner.value(QStringLiteral("task_status")).toString(); // complete 只有与任务终态同时出现才可推进本地队列。 const bool terminalTask = taskStatus == QStringLiteral("completed") || taskStatus == QStringLiteral("failed") || taskStatus == QStringLiteral("interrupted"); // task_complete 推送与 GetCommand 可能描述同一轮终态:按 boot_id 跨通道去重, // 防止先收到推送推进到下一任务后,又被迟到的 GetCommand 把下一任务误推进一次。 const bool alreadyReportedForBoot = !m_bootId[station].isEmpty() && m_lastTaskCompleteBoot[station] == m_bootId[station]; // 换条停机(run_state=blocked)期间不再上报 complete:命令结果包可能比 state 包先到, // 那时上层还没看到 awaiting_dimm_replacement,会误把队列推进到下一条任务。 if (complete && terminalTask && !alreadyReportedForBoot && !m_blockedWarned[station] && m_lastCompleteCmd[station] != commandId) { m_lastCompleteCmd[station] = commandId; m_lastTaskStatus[station] = taskStatus; if (!m_bootId[station].isEmpty()) m_lastTaskCompleteBoot[station] = m_bootId[station]; emit taskProgressReported(station, true, taskStatus); } else if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) { m_lastTaskStatus[station] = taskStatus; emit taskProgressReported(station, false, taskStatus); } } // 手册 9.5:确认已更换 DIMM,清除后端换条停机挂起(awaiting_dimm_replacement)。 void BackendLink::confirmDimmReplacement(int station) { if (station < 0 || station >= kStationCount) return; if (!isConnected()) { emit dimmConfirmed(station, false, QStringLiteral("后端未连接")); return; } const QString commandId = newCommandId(QStringLiteral("dimm"), station); QJsonObject params; params.insert(QStringLiteral("command_id"), commandId); params.insert(QStringLiteral("station_id"), stationId(station)); // ConfirmDimmReplacement 只要求 command_id + station_id。 // 该工位可能因为 blocked 被暂停自动下发,确认换条后恢复(下一轮 boot_id 也会再清一次)。 m_stationPaused[station] = false; m_blockedWarned[station] = false; emit logLine(station, QStringLiteral("[qt] 提交更换异常内存条确认(%1)").arg(commandId)); sendRequest(QStringLiteral("ConfirmDimmReplacement"), params, [this, station](const QJsonObject &result) { const QString state = result.value(QStringLiteral("state")).toString(); if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) { const QJsonObject err = result.value(QStringLiteral("error")).toObject(); const QString msg = QStringLiteral("%1 %2") .arg(err.value(QStringLiteral("code")).toString(), err.value(QStringLiteral("message")).toString()) .trimmed(); emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg)); emit dimmConfirmed(station, false, msg); return; } emit logLine(station, QStringLiteral("[qt] 已确认更换异常内存条,后端换条停机挂起已解除")); m_stageErrorsJson[station].clear(); m_lastVerdict[station].clear(); emit dimmConfirmed(station, true, QString()); }, [this, station](const QString &code, const QString &message) { const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed(); emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg)); emit dimmConfirmed(station, false, msg); }); } void BackendLink::applyState(const QJsonObject &result) { const QString serverId = result.value(QStringLiteral("server_id")).toString(); if (!m_serverId.isEmpty() && serverId != m_serverId) { // 后端重启:清掉旧输入节点与在途/自动运行归属,不重放任何动作,防止 canSubmitStart 永久锁死 qInfo().noquote() << "[backend] server_id 变化,清理旧输入节点与在途/自动运行状态"; m_autoPaused = true; for (int i = 0; i < kStationCount; ++i) { m_handledInput[i].clear(); m_appliedCpu[i].clear(); m_bootId[i].clear(); m_lastTaskCompleteBoot[i].clear(); m_lastTaskCompleteEventBoot[i].clear(); m_stageDoneKeys[i].clear(); m_stagePendingCmd[i].clear(); m_stagePendingKey[i].clear(); m_stageIntentPending[i].clear(); m_stageIntentReady[i].clear(); m_waitingNewBoot[i] = false; m_stationPaused[i] = false; m_blockedWarned[i] = false; m_lastCompleteCmd[i].clear(); m_lastTaskStatus[i].clear(); m_stageErrorsJson[i].clear(); m_lastVerdict[i].clear(); m_lastCanStart[i] = true; m_startRpcInFlight[i] = false; const bool hadStartPending = m_startPending[i]; m_startPending[i] = false; m_startCmd[i].clear(); if (!m_fileQueryCmd[i].isEmpty()) { m_fileQueryCmd[i].clear(); emit uefiFilesArrived(i, false, m_fileQueryPath[i], QStringList(), QStringLiteral("后端已重启,请重试")); } if (hadStartPending) emit startTestReplied(i, false, QStringLiteral("后端实例已重启")); } m_pending.clear(); m_pollCount.clear(); m_pendingSince.clear(); emit serverRestarted(); } m_serverId = serverId; const QJsonArray stations = result.value(QStringLiteral("stations")).toArray(); for (const QJsonValue &v : stations) { const QJsonObject st = v.toObject(); const int index = stationIndex(st.value(QStringLiteral("station_id")).toString()); if (index < 0) continue; emit stateArrived(index, st); applyStation(index, st); autoPlan(index, st); } } void BackendLink::applyStation(int station, const QJsonObject &st) { // 设备连接状态变化:没 BIOS 日志时先用它区分「后端根本没串口数据」和「Qt 端丢字节」 const QString conn = st.value(QStringLiteral("connection")).toString(); // 顺带记住 power / phase / run_state:控制台报 offline 时这三个值能区分 // 「后端根本没连上主机」和「主机在跑、只是控制台通道断了」,日志和界面都要用 m_lastPower[station] = st.value(QStringLiteral("power")).toString(); m_lastPhase[station] = st.value(QStringLiteral("phase")).toString(); m_lastRun[station] = st.value(QStringLiteral("run_state")).toString(); m_lastCanStart[station] = st.value(QStringLiteral("can_start")).toBool(false); if (!conn.isEmpty() && conn != m_lastConn[station]) { m_lastConn[station] = conn; m_connOfflineWarned[station] = false; // 状态变过,允许再提示一次 qInfo().noquote() << "[backend] 工位" << stationId(station) << "connection =" << conn << " power =" << m_lastPower[station] << " phase =" << m_lastPhase[station] << " run_state =" << m_lastRun[station]; } // 当前固件输入节点:list_uefi_files 之类的手动动作要原样带回去 m_lastInputId[station] = st.value(QStringLiteral("input")).toObject() .value(QStringLiteral("id")).toString(); // boot_id 变化 = 新一轮启动:内存参数要在新的 ICT1 重新下发 const QString bootId = st.value(QStringLiteral("boot_id")).toString(); if (!bootId.isEmpty() && bootId != m_bootId[station]) { m_bootId[station] = bootId; m_appliedCpu[station].clear(); m_handledInput[station].clear(); m_stageDoneKeys[station].clear(); m_stagePendingCmd[station].clear(); m_stagePendingKey[station].clear(); m_stationPaused[station] = false; // 新一轮启动,恢复自动化 m_blockedWarned[station] = false; // 新一轮允许重新提示换条停机 m_lastCompleteCmd[station].clear(); // 新任务允许再报一次 complete m_lastTaskCompleteBoot[station].clear(); m_waitingNewBoot[station] = false; m_lastTaskStatus[station].clear(); m_stageErrorsJson[station].clear(); // 新一轮允许重新报告相同内容 m_lastVerdict[station].clear(); // 新一轮的 verdict 重新计 } // 0.8.1.13:stage_errors 按 training / rmt / amt / mt 分类给出本轮结构化 // 阶段错误与通道禁用明细。state 每秒推送一次 —— 内容没变就不重复刷日志。 const QJsonObject stageErrors = st.value(QStringLiteral("stage_errors")).toObject(); if (!stageErrors.isEmpty()) { const QString compact = QString::fromUtf8( QJsonDocument(stageErrors).toJson(QJsonDocument::Compact)); if (compact != m_stageErrorsJson[station]) { m_stageErrorsJson[station] = compact; const char *const kStages[] = {"training", "rmt", "amt", "mt", "system"}; for (const char *stage : kStages) { const QJsonArray errors = stageErrors.value(QString::fromLatin1(stage)).toArray(); if (errors.isEmpty()) continue; const QString detail = QString::fromUtf8( QJsonDocument(errors).toJson(QJsonDocument::Compact)); emit logLine(station, QStringLiteral("[qt] 阶段错误(%1):%2") .arg(QString::fromLatin1(stage), detail)); // 同时落成一条条可读的异常记录(详情页第二个标签页) for (const QJsonValue &item : errors) { QString rawKey; const QString text = describeStageError(item, &rawKey); if (!text.isEmpty()) emit alarmReported(station, QString::fromLatin1(stage), text, rawKey); } } } } // verdict 只在「刚变成 fail」的那一下记一条:state 每秒推送,不盯着变化会刷屏。 // boot_id 变化时 m_lastVerdict 已清空,新一轮重新计。 const QString verdict = st.value(QStringLiteral("verdict")).toString(); if (!verdict.isEmpty() && verdict != m_lastVerdict[station]) { m_lastVerdict[station] = verdict; if (verdict == QStringLiteral("fail")) { const QString scope = st.value(QStringLiteral("verdict_scope")).toString(); emit alarmReported(station, scope, scope.isEmpty() ? QStringLiteral("本轮判定 FAIL") : QStringLiteral("本轮判定 FAIL(%1 阶段)").arg(scope)); } } // 手册 9.2:state 推送的 station.command 同样带 complete / task_status; // 工位对象自己也有 task_status,变化时才上报(每秒一包,不去重会刷屏)。 const QJsonObject command = st.value(QStringLiteral("command")).toObject(); if (!command.isEmpty()) reportCommandProgress(station, command.value(QStringLiteral("command_id")).toString(), command); const QString taskStatus = st.value(QStringLiteral("task_status")).toString(); if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) { m_lastTaskStatus[station] = taskStatus; emit taskProgressReported(station, false, taskStatus); } // 手册 9.2/9.5:阶段 FAIL 后后端把 run_state 置为 blocked 并挂起换条, // 此时停止该工位的自动下发,等测试员换条后点「开始测试」强制重启新一轮。 const QString runState = st.value(QStringLiteral("run_state")).toString(); const bool awaitingDimm = st.value(QStringLiteral("awaiting_dimm_replacement")).toBool(); if ((runState == QStringLiteral("blocked") || awaitingDimm) && !m_blockedWarned[station]) { m_blockedWarned[station] = true; m_stationPaused[station] = true; emit logLine(station, QStringLiteral("[qt] 后端换条停机(run_state=blocked):本阶段已跑完," "等待更换异常内存条;换好后点「开始测试」可强制重启新一轮")); emit alarmReported(station, QString(), QStringLiteral("换条停机:等待更换异常内存条并重新开始测试")); } // FAIL / STOPPED / ABORTED 之后该工位停止自动动作,等人工处理(其他工位不受影响) if (runState == QStringLiteral("failed") || runState == QStringLiteral("stopped") || runState == QStringLiteral("interrupted") || runState == QStringLiteral("aborted") || runState == QStringLiteral("error") || runState == QStringLiteral("timeout")) { if (!m_stationPaused[station]) { qInfo().noquote() << "[backend] 工位" << stationId(station) << "进入" << runState << ",暂停该工位自动下发"; m_stationPaused[station] = true; } } } // 0.8.1.19:在新的 StartTest 已受理后,将四个阶段意图提前写入后端。 // 每个阶段的最后一次意图由后端 Last-Write-Wins 规则决定;成功预置后不再 // 在 input.ready 时重复发送 StageAction,防止后端自动消费与前端动作撞车。 void BackendLink::stageStationIntents(int station) { if (station < 0 || station >= kStationCount || !isConnected()) return; m_stageIntentPending[station].clear(); m_stageIntentReady[station].clear(); auto sendIntent = [this, station](const QString &stage, const QString &action, const QJsonObject &extra) { m_stageIntentPending[station].insert(stage); QJsonObject params; params.insert(QStringLiteral("command_id"), newCommandId(QStringLiteral("intent-") + stage, station)); params.insert(QStringLiteral("station_id"), stationId(station)); params.insert(QStringLiteral("stage"), stage); params.insert(QStringLiteral("action"), action); for (auto it = extra.constBegin(); it != extra.constEnd(); ++it) params.insert(it.key(), it.value()); sendRequest(QStringLiteral("SetStageIntent"), params, [this, station, stage, action](const QJsonObject &result) { m_stageIntentPending[station].remove(stage); const QString confirmation = result.value(QStringLiteral("confirmation")).toString(); const QString respStage = result.value(QStringLiteral("stage")).toString(); QString stageText = ui::inputStageText(stage); if (stageText == stage) stageText = stage.toUpper(); if (confirmation == QStringLiteral("staged") && (respStage.isEmpty() || respStage == stage)) { m_stageIntentReady[station].insert(stage); emit logLine(station, QStringLiteral("[qt] 阶段意图已预置:%1 / %2(staged)") .arg(stageText, action)); } else { // 只有明确返回 staged 且阶段匹配才能认定后端已接管;否则保留 input.ready 回退路径。 m_stageIntentReady[station].remove(stage); emit logLine(station, QStringLiteral("[qt] %1 阶段未确认预置(confirmation=%2, stage=%3),到达提示符后回退普通动作") .arg(stageText, confirmation.isEmpty() ? QStringLiteral("missing") : confirmation, respStage.isEmpty() ? QStringLiteral("missing") : respStage)); } }, [this, station, stage, action](const QString &code, const QString &message) { // 旧版后端不支持 SetStageIntent 时自动回退到 input.ready -> StageAction。 m_stageIntentPending[station].remove(stage); m_stageIntentReady[station].remove(stage); emit logLine(station, QStringLiteral("[qt] %1 阶段预置失败(%2 %3),到达提示符后回退普通动作") .arg(stage, code, message)); }); }; // ICT1:完整透传本地 memory_params(即使为空对象也透传以清掉上一轮残留覆写)与 rmt(含 selected/enabled),并单独指定 RMT 开关。 QJsonObject ict1; const bool runRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true); ict1.insert(QStringLiteral("run_rmt"), runRmt); if (!m_rmtParams[station].isEmpty()) ict1.insert(QStringLiteral("rmt"), m_rmtParams[station]); ict1.insert(QStringLiteral("memory_params"), m_memoryParams[station]); sendIntent(QStringLiteral("uip1"), QStringLiteral("continue_uip"), ict1); // AMT:按启用开关预置 start_amt / skip_amt;selected、only_tests、skip_tests 均透传。 const QJsonObject amt = m_amtParams[station]; const bool runAmt = amt.value(QStringLiteral("enabled")).toBool(true); QJsonObject amtExtra; amtExtra.insert(QStringLiteral("run_amt"), runAmt); if (runAmt) { QJsonObject payload; QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed(); if (testCommand.isEmpty()) testCommand = QStringLiteral("amemdiag 1"); payload.insert(QStringLiteral("test_command"), testCommand); const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"}; for (const char *key : amtKeys) { const QJsonValue value = amt.value(QLatin1String(key)); if (!value.isUndefined() && !value.isNull() && (!value.isArray() || !value.toArray().isEmpty())) payload.insert(QLatin1String(key), value); } if (amt.contains(QStringLiteral("end_step"))) payload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step"))); amtExtra.insert(QStringLiteral("amt"), payload); } sendIntent(QStringLiteral("amt"), runAmt ? QStringLiteral("start_amt") : QStringLiteral("skip_amt"), amtExtra); // ICT2:继续固件流程,不重复应用 ICT1 参数。 sendIntent(QStringLiteral("uip2"), QStringLiteral("continue_uip"), QJsonObject()); // MT:后端按 mt86.cfg / PXE 规则处理文件与地址范围;这里只传本地明确配置项。 const QJsonObject mt = m_mtParams[station]; const bool runMt = mt.value(QStringLiteral("enabled")).toBool(true); QJsonObject mtExtra; mtExtra.insert(QStringLiteral("run_mt"), runMt); if (runMt) { const QJsonObject payload = LocalPlans::mtStagePayload(mt); if (!payload.isEmpty()) mtExtra.insert(QStringLiteral("mt"), payload); } sendIntent(QStringLiteral("mt"), runMt ? QStringLiteral("start_mt") : QStringLiteral("skip_mt"), mtExtra); } void BackendLink::autoPlan(int station, const QJsonObject &st) { if (m_autoPaused || m_stationPaused[station] || m_startRpcInFlight[station]) return; // 一个动作到终态才处理下一个输入节点:有在途阶段动作就先等着, // 否则会在同一个提示符上连发 CR,后端回 FAILED_PRECONDITION(输入节点已变化) if (!m_stagePendingCmd[station].isEmpty()) return; const QJsonObject input = st.value(QStringLiteral("input")).toObject(); if (input.isEmpty() || !input.value(QStringLiteral("ready")).toBool()) return; const QString inputId = input.value(QStringLiteral("id")).toString(); if (inputId.isEmpty()) return; const QString stage = input.value(QStringLiteral("stage")).toString(); const int cpu = input.value(QStringLiteral("cpu")).toInt(0); const bool testComplete = input.value(QStringLiteral("test_complete")).toBool(); // 去重键用「阶段 + CPU」:UIP 提示符每回车一次 input.id 就变,按 id 去重会重复发 QString key = QStringLiteral("%1/%2").arg(stage).arg(cpu); // 手册 3.2/3.4:AMT 跑完后菜单会再次就绪,这一次要发的是 skip_amt(exit), // 和前面的 start_amt 是两个不同动作。用独立去重键,否则会被「同阶段只处理一次」挡掉, // 结果就是一直停在 AMT 菜单、整轮测试卡死。 const bool amtWanted = m_amtParams[station].value(QStringLiteral("enabled")).toBool(true); if (stage == QStringLiteral("amt") && testComplete && amtWanted) key = QStringLiteral("amt-exit/%1").arg(cpu); // SetStageIntent 已成功预置时,后端会在该阶段提示符自动消费; // AMT 跑完后后端也会按 exit_after=true 自动提交 exit,不重复发送 skip_amt。 const QString intentStage = (stage == QStringLiteral("uefi")) ? QStringLiteral("mt") : stage; if (m_stageIntentPending[station].contains(intentStage) || m_stageIntentReady[station].contains(intentStage)) return; if (m_stageDoneKeys[station].contains(key)) return; QString action; QJsonObject extra; if (stage == QStringLiteral("uip1")) { // 每个 CPU 的 ICT1 各下发一次内存参数;同一 CPU 再次进入 ICT1 只发空回车。 // 手册 3.4:ICT1 的 continue_uip 要带 run_rmt(默认 true),后端据此决定 // 下发 rmt enable 跑完整 RMT 扫描,还是直接空回车跳过。 action = QStringLiteral("continue_uip"); const bool wantRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true); extra.insert(QStringLiteral("run_rmt"), wantRmt); if (!m_rmtParams[station].isEmpty()) extra.insert(QStringLiteral("rmt"), m_rmtParams[station]); if (!m_appliedCpu[station].contains(cpu) && !m_memoryParams[station].isEmpty()) { extra.insert(QStringLiteral("memory_params"), m_memoryParams[station]); m_appliedCpu[station].insert(cpu); } } else if (stage == QStringLiteral("uip2")) { action = QStringLiteral("continue_uip"); // 空参数,只发一个 CR } else if (stage == QStringLiteral("amt")) { // AMT 菜单:勾了「启用 AMT 测试」就 start_amt(手册 3.4 的极简模式: // run_amt + amt.test_command,默认 amemdiag 1),否则 skip_amt 发 exit。 // 双 CPU 菜单逐个处理;input.test_complete 为真说明这颗 CPU 的 19 项算法 // 已经跑出有效 PASS,此时必须由前端发 skip_amt 退出菜单。 const QJsonObject amt = m_amtParams[station]; if (amt.value(QStringLiteral("enabled")).toBool(true)) { if (testComplete) { action = QStringLiteral("skip_amt"); // 跑完了,退出当前 CPU 的 AMT 菜单 } else { action = QStringLiteral("start_amt"); extra.insert(QStringLiteral("run_amt"), true); // 只带测试命令;旧版 overrides / raw_commands 纯净接口会忽略,不再传 QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed(); if (testCommand.isEmpty()) testCommand = QStringLiteral("amemdiag 1"); QJsonObject amtPayload; amtPayload.insert(QStringLiteral("test_command"), testCommand); // 手册 9.4:后端按 amt.selected(或 only_tests / skip_tests)自动生成 // 合规的 tp 表指令;end_step=0 可单步快跑全部算法。没勾就完全不传, // 由后端按默认「19 项全跑」执行,避免把空数组误读成「一项都不跑」。 const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"}; for (const char *key : amtKeys) { const QJsonValue value = amt.value(QLatin1String(key)); if (!value.isUndefined() && !value.isNull() && (!value.isArray() || !value.toArray().isEmpty())) amtPayload.insert(QLatin1String(key), value); } if (amt.contains(QStringLiteral("end_step"))) amtPayload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step"))); extra.insert(QStringLiteral("amt"), amtPayload); } } else { action = QStringLiteral("skip_amt"); } } else if (stage == QStringLiteral("uefi")) { // UEFI Shell(MT 阶段):勾了「启用 MT 测试」就 start_mt, // 后端在 Shell> 下自动 fs0: → cd EFI → 写 mt86.cfg → 118.efi; // 不勾就 skip_mt,直接按已执行阶段汇总 verdict。每颗 CPU 的 Shell 各处理一次。 const QJsonObject mt = m_mtParams[station]; if (mt.value(QStringLiteral("enabled")).toBool(true)) { action = QStringLiteral("start_mt"); // 手册 0.8.1.13:mt 支持 efi_path / config_path / memory_range / // addr_lim_lo / addr_lim_hi / exit_mode / only_tests / skip_tests。 // 只下发本地显式配置过的键;空对象则完全走后端默认。 const QJsonObject mtPayload = LocalPlans::mtStagePayload(mt); if (!mtPayload.isEmpty()) extra.insert(QStringLiteral("mt"), mtPayload); } else { action = QStringLiteral("skip_mt"); } } else { return; } // 只发当前真正允许的动作(手册:input.actions 是此刻可用的动作) const QJsonArray allowed = input.value(QStringLiteral("actions")).toArray(); if (!allowed.isEmpty()) { bool ok = false; for (const QJsonValue &v : allowed) { if (v.toString() == action) { ok = true; break; } } if (!ok) { QString stageText = ui::inputStageText(stage); if (stageText == stage) stageText = stage.toUpper(); qInfo().noquote() << "[backend] 工位" << stationId(station) << stageText << "当前不允许" << action << ",等待状态变化"; return; } } m_handledInput[station] = inputId; m_stageDoneKeys[station].insert(key); // 同一阶段+CPU 只处理一次,等阶段推进 m_stagePendingKey[station] = key; submitStageAction(station, inputId, action, extra); } void BackendLink::submitStageAction(int station, const QString &inputId, const QString &action, const QJsonObject &extra) { const QString commandId = newCommandId(QStringLiteral("stage"), station); QJsonObject params; params.insert(QStringLiteral("command_id"), commandId); params.insert(QStringLiteral("station_id"), stationId(station)); params.insert(QStringLiteral("input_id"), inputId); params.insert(QStringLiteral("action"), action); for (QJsonObject::const_iterator it = extra.constBegin(); it != extra.constEnd(); ++it) params.insert(it.key(), it.value()); trackCommand(commandId, station); m_stagePendingCmd[station] = commandId; // 在途:终态前不再发下一个节点 emit logLine(station, QStringLiteral("[qt] %1 → %2(input=%3)") .arg(stationId(station), action, inputId.left(12))); sendRequest(QStringLiteral("StageAction"), params, [this, commandId, station](const QJsonObject &result) { const QString state = result.value(QStringLiteral("state")).toString(); qInfo().noquote() << "[backend] StageAction" << commandId << "state =" << state; reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) { forgetCommand(commandId); if (m_stagePendingCmd[station] == commandId) m_stagePendingCmd[station].clear(); const QJsonObject err = result.value(QStringLiteral("error")).toObject(); const QString code = err.value(QStringLiteral("code")).toString(); const QString msg = err.value(QStringLiteral("message")).toString(); emit logLine(station, QStringLiteral("[qt] 阶段动作 %1:%2 %3") .arg(state, code, msg).trimmed()); if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) { m_stageDoneKeys[station].remove(m_stagePendingKey[station]); } else { m_stationPaused[station] = true; emit logLine(station, QStringLiteral("[qt] 阶段动作 %1(已暂停该工位自动下发)").arg(state)); } } else if (state == QStringLiteral("succeeded")) { forgetCommand(commandId); if (m_stagePendingCmd[station] == commandId) m_stagePendingCmd[station].clear(); } }, [this, commandId, station](const QString &code, const QString &message) { forgetCommand(commandId); if (m_stagePendingCmd[station] == commandId) m_stagePendingCmd[station].clear(); emit logLine(station, QStringLiteral("[qt] 阶段动作被后端拒绝:%1 %2").arg(code, message).trimmed()); if (code == QStringLiteral("FAILED_PRECONDITION")) m_stageDoneKeys[station].remove(m_stagePendingKey[station]); else m_stationPaused[station] = true; }); } bool BackendLink::startTest(int station, bool continueTimer) { if (station < 0 || station >= kStationCount) return false; // 必须先判连接:没连上还往下走的话,请求会被 sendRequest 直接丢掉, // m_startPending 永远为 true → 之后每次点击都被当成重复点击吞掉(表现为按钮点不动) if (!isConnected()) { qInfo().noquote() << "[backend] 未连接后端,忽略" << stationId(station) << "的开始测试"; emit logLine(station, QStringLiteral("[qt] 后端未连接,无法开始测试")); return false; } // 记下这次点击是不是「跑着的时候点的」:界面要据此忽略复位过程中的 idle, // 否则新一轮刚开始按钮就会闪回「开始测试」。 m_restartFromRunning[station] = (m_lastRun[station] == QStringLiteral("running") || m_lastRun[station] == QStringLiteral("waiting_input") || m_lastRun[station] == QStringLiteral("starting")); // 现场口径:总览页点「开始测试 / 重新开始」就必须重新开始,不管主机当前在跑什么。 // 后端 StartTest 本身语义就是「已开机则复位、已关机则开机」,所以这里不按 // can_start 拦(那是「有没有冲突操作」的判据,测试进行中必然是 false)。 // 只在确实有冲突时留一条日志,方便事后对上是把哪一轮复位掉的。 if (!m_lastCanStart[station]) { const QString phase = m_lastPhase[station].isEmpty() ? QStringLiteral("unknown") : m_lastPhase[station]; const QString run = m_lastRun[station].isEmpty() ? QStringLiteral("unknown") : m_lastRun[station]; qInfo().noquote() << "[backend]" << stationId(station) << "can_start = false(phase =" << phase << " run_state =" << run << "),仍提交 StartTest,由后端裁决"; emit logLine(station, QStringLiteral("[qt] 当前 %1(run_state=%2)can_start=false," "照常提交 StartTest,由后端裁决").arg(phase, run)); } // connection 报 offline:不拦。后端可能只是重启后没刷新(陈旧值), // 真正能不能做由后端在 StartTest 里重新核验,这里只留一句提示便于对日志。 if (m_lastConn[station] == QStringLiteral("offline")) { const QString power = m_lastPower[station].isEmpty() ? QStringLiteral("unknown") : m_lastPower[station]; const QString phase = m_lastPhase[station].isEmpty() ? QStringLiteral("unknown") : m_lastPhase[station]; qInfo().noquote() << "[backend]" << stationId(station) << "connection 报 offline,仍提交 StartTest,由后端重新核验" << " power =" << power << " phase =" << phase; emit logLine(station, QStringLiteral("[qt] 注意:后端报控制台 offline(power=%1, phase=%2)," "照常提交开始测试,由后端核验").arg(power, phase)); } // 同一工位已有未结束的 StartTest:拒绝重复排入(后端也会拒),直接告诉调用方 if (m_startPending[station] || m_startRpcInFlight[station]) { qInfo().noquote() << "[backend]" << stationId(station) << "已有未完成的 StartTest" << m_startCmd[station] << ",忽略本次点击"; emit logLine(station, QStringLiteral("[qt] 该工位已有未完成的 StartTest,忽略本次点击")); return false; } const QString commandId = newCommandId(QStringLiteral("start"), station); // 新一轮:清掉上一轮残留的输入节点与 CPU 参数下发记录 m_handledInput[station].clear(); m_appliedCpu[station].clear(); m_stageDoneKeys[station].clear(); m_stagePendingCmd[station].clear(); m_stagePendingKey[station].clear(); m_stageIntentPending[station].clear(); m_stageIntentReady[station].clear(); m_stationPaused[station] = false; m_blockedWarned[station] = false; m_autoPaused = false; m_waitingNewBoot[station] = true; // 日志区会被上层清空:短时间内丢弃旧会话的残留字节,等新会话再显示。 // 注意必须是「限时」静音:后端在一次重启前后可能沿用同一个会话编号, // 只按 session 变化解除的话会永久静音(表现为开始测试后一条 BIOS 日志都没有)。 m_uartMuted[station] = true; m_uartMuteMs[station] = nowMs(); m_uartDropped[station] = 0; m_uartPending[station].clear(); m_uartLastWasCr[station] = false; QJsonObject params; params.insert(QStringLiteral("command_id"), commandId); params.insert(QStringLiteral("station_id"), stationId(station)); if (continueTimer) params.insert(QStringLiteral("continue_timer"), true); trackCommand(commandId, station); m_startPending[station] = true; m_startRpcInFlight[station] = true; m_startCmd[station] = commandId; emit logLine(station, QStringLiteral("[qt] 已请求后端 StartTest(%1)").arg(commandId)); sendRequest(QStringLiteral("StartTest"), params, [this, station, commandId](const QJsonObject &result) { m_startRpcInFlight[station] = false; const QString state = result.value(QStringLiteral("state")).toString(); qInfo().noquote() << "[backend] StartTest" << commandId << "state =" << state; reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status if (state == QStringLiteral("queued") || state == QStringLiteral("running") || state == QStringLiteral("dispatching")) { // StartTest 已受理,当前旧启动已被后端接管;现在预置新一轮四阶段意图, // 请求帧按 WebSocket 顺序先于后续阶段状态处理,不会抢写旧 BIOS 会话。 stageStationIntents(station); emit logLine(station, QStringLiteral("[qt] StartTest 已受理(%1),等待新 BIOS 启动与可交互输入") .arg(state)); emit startTestReplied(station, true, state); } else if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) { forgetCommand(commandId); m_startPending[station] = false; m_waitingNewBoot[station] = false; if (m_startCmd[station] == commandId) m_startCmd[station].clear(); m_stationPaused[station] = true; const QJsonObject err = result.value(QStringLiteral("error")).toObject(); const QString code = err.value(QStringLiteral("code")).toString(); const QString msg = err.value(QStringLiteral("message")).toString(); emit logLine(station, QStringLiteral("[qt] StartTest %1:%2 %3").arg(state, code, msg)); emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, msg).trimmed()); } else if (state == QStringLiteral("succeeded")) { forgetCommand(commandId); const QJsonObject resObj = result.value(QStringLiteral("result")).toObject(); const QString prevBoot = resObj.value(QStringLiteral("previous_boot_id")).toString(); const QString newBoot = resObj.value(QStringLiteral("boot_id")).toString(); if (!newBoot.isEmpty() && newBoot == prevBoot) { // 纯串口无 BMC 复位工位 StartTest 不递增 boot_id,避免 m_waitingNewBoot 吞掉本轮终态 m_waitingNewBoot[station] = false; } // 直接终态(复位/开机已确认并进入可交互窗口),仍先预置后续阶段意图。 stageStationIntents(station); m_startPending[station] = false; if (m_startCmd[station] == commandId) m_startCmd[station].clear(); emit startTestReplied(station, true, state); } }, [this, station, commandId](const QString &code, const QString &message) { m_startRpcInFlight[station] = false; m_waitingNewBoot[station] = false; forgetCommand(commandId); // 后端在 RPC 层直接拒掉 StartTest(典型:FAILED_PRECONDITION, // 该工位正被另一个客户端/网页端执行)。此时不会有任何命令记录, // 必须在这里就把在途闸门放开、并通知界面复位按钮, // 否则界面一直停在「执行中」,后续点击还会被「已有未完成 StartTest」吞掉。 if (m_startCmd[station] == commandId) { m_startCmd[station].clear(); m_startPending[station] = false; } qInfo().noquote() << "[backend] StartTest" << commandId << "被拒绝:" << code << message; emit logLine(station, QStringLiteral("[qt] 开始测试被后端拒绝:%1 %2").arg(code, message)); emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, message).trimmed()); }); return true; } namespace { /** result.files 里每项是 {name, path, kind, size_bytes},界面只需要名字 */ QStringList uefiFileNames(const QJsonObject &result) { QStringList files; const QJsonArray arr = result.value(QStringLiteral("files")).toArray(); for (const QJsonValue &v : arr) { const QJsonObject f = v.toObject(); const QString name = f.value(QStringLiteral("name")).toString(); if (!name.isEmpty()) files << name; } return files; } /** 后端的 error 是 {code, message},转成一句能直接显示的话 */ QString rpcErrorText(const QJsonObject &result) { const QJsonObject err = result.value(QStringLiteral("error")).toObject(); return QStringLiteral("%1 %2") .arg(err.value(QStringLiteral("code")).toString(), err.value(QStringLiteral("message")).toString()) .trimmed(); } } // namespace void BackendLink::listUefiFiles(int station, const QString &path) { if (station < 0 || station >= kStationCount) return; if (!isConnected()) { emit uefiFilesArrived(station, false, path, QStringList(), QStringLiteral("后端未连接")); return; } if (!m_fileQueryCmd[station].isEmpty()) { emit uefiFilesArrived(station, false, path, QStringList(), QStringLiteral("上一次目录查询还没结束")); return; } const QString commandId = newCommandId(QStringLiteral("dir"), station); QJsonObject params; params.insert(QStringLiteral("command_id"), commandId); params.insert(QStringLiteral("station_id"), stationId(station)); if (!m_lastInputId[station].isEmpty()) params.insert(QStringLiteral("input_id"), m_lastInputId[station]); params.insert(QStringLiteral("action"), QStringLiteral("list_uefi_files")); params.insert(QStringLiteral("path"), path); m_fileQueryCmd[station] = commandId; m_fileQueryPath[station] = path; trackCommand(commandId, station); emit logLine(station, QStringLiteral("[qt] 查询 UEFI 目录 %1(%2)").arg(path, commandId)); sendRequest(QStringLiteral("StageAction"), params, [this, station, commandId](const QJsonObject &result) { const QString state = result.value(QStringLiteral("state")).toString(); qInfo().noquote() << "[backend] list_uefi_files" << commandId << "state =" << state; // 后端也可能直接同步跑完(缓存命中),那就当场给结果,不必等轮询 if (state == QStringLiteral("succeeded")) { if (m_fileQueryCmd[station] == commandId) { forgetCommand(commandId); m_fileQueryCmd[station].clear(); emit uefiFilesArrived(station, true, m_fileQueryPath[station], uefiFileNames(result), QString()); } return; } if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) { if (m_fileQueryCmd[station] == commandId) { forgetCommand(commandId); m_fileQueryCmd[station].clear(); const QString msg = rpcErrorText(result); emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg)); emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg); } } }, [this, station, commandId](const QString &code, const QString &message) { if (m_fileQueryCmd[station] != commandId) return; // 已被别的路径处理过,别重复弹窗 forgetCommand(commandId); m_fileQueryCmd[station].clear(); const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed(); emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg)); emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg); }); } void BackendLink::trackCommand(const QString &commandId, int station) { m_pending.insert(commandId, station); m_pollCount.insert(commandId, 0); m_pendingSince.insert(commandId, QDateTime::currentMSecsSinceEpoch()); } void BackendLink::forgetCommand(const QString &commandId) { m_pending.remove(commandId); m_pollCount.remove(commandId); m_pendingSince.remove(commandId); } void BackendLink::pollPending() { if (!isConnected()) return; const qint64 now = QDateTime::currentMSecsSinceEpoch(); const QStringList ids = m_pending.keys(); for (const QString &commandId : ids) { // 刚发出去的命令后端还没落记录,这时候问 GetCommand 只会拿到 NOT_FOUND。 // 以前就在这里被误判成失败、直接停止跟踪,于是命令真正的结果永远回不来 // (界面表现:点了「扫描 EFI」没有任何反应)。 if (now - m_pendingSince.value(commandId, 0) < kPollGraceMs) continue; const int n = m_pollCount.value(commandId, 0) + 1; m_pollCount.insert(commandId, n); if (n > 15) { // 约 30s 仍拿不到记录:多为后端没接受该命令,停止轮询 const int station = m_pending.value(commandId, -1); forgetCommand(commandId); if (station >= 0) { // 在途闸门要放开,否则该工位会一直卡着不再自动下发 if (m_stagePendingCmd[station] == commandId) m_stagePendingCmd[station].clear(); // StartTest 也一样:后端查不到这条记录时必须放开, // 否则 m_startPending 永远为 true,之后每次点击「开始测试」都被吞掉 if (m_startCmd[station] == commandId) { m_startCmd[station].clear(); m_startPending[station] = false; emit startTestReplied(station, false, QStringLiteral("命令 %1 查询不到记录").arg(commandId)); } if (m_fileQueryCmd[station] == commandId) { m_fileQueryCmd[station].clear(); emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), QStringLiteral("命令 %1 查询不到记录").arg(commandId)); } emit logLine(station, QStringLiteral("[qt] 命令 %1 查询不到记录,已停止跟踪").arg(commandId)); } continue; } pollCommand(commandId); } } void BackendLink::pollCommand(const QString &commandId) { QJsonObject params; params.insert(QStringLiteral("command_id"), commandId); sendRequest(QStringLiteral("GetCommand"), params, [this, commandId](const QJsonObject &result) { const QString state = result.value(QStringLiteral("state")).toString(); const int station = m_pending.value(commandId, -1); reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status const bool terminal = (state == QStringLiteral("succeeded") || state == QStringLiteral("failed") || state == QStringLiteral("interrupted")); const bool isStartCommand = station >= 0 && m_startCmd[station] == commandId; if (terminal) { forgetCommand(commandId); if (isStartCommand) { m_startCmd[station].clear(); m_startPending[station] = false; // 放开工位,允许再次点「开始测试」 } else if (station >= 0 && m_stagePendingCmd[station] == commandId) { m_stagePendingCmd[station].clear();// 阶段动作结束,可以处理下一个节点 } // 目录浏览(0.8.1.14 list_uefi_files):结果在 result.files if (station >= 0 && m_fileQueryCmd[station] == commandId) { m_fileQueryCmd[station].clear(); const QString path = m_fileQueryPath[station]; if (state == QStringLiteral("succeeded")) emit uefiFilesArrived(station, true, path, uefiFileNames(result), QString()); else emit uefiFilesArrived(station, false, path, QStringList(), rpcErrorText(result)); } } if (station >= 0 && (state == QStringLiteral("failed") || state == QStringLiteral("interrupted"))) { const QJsonObject err = result.value(QStringLiteral("error")).toObject(); const QString code = err.value(QStringLiteral("code")).toString(); const QString msg = err.value(QStringLiteral("message")).toString(); emit logLine(station, QStringLiteral("[qt] 命令 %1 %2:%3 %4") .arg(commandId, state == QStringLiteral("interrupted") ? QStringLiteral("中断") : QStringLiteral("失败"), code, msg)); // 输入节点已变化:撤回该节点的「已完成」标记,等新状态用新 input.id 重试; // 其他错误(链路不可用 / 后端 INTERNAL 等)才真正暂停该工位。 if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) { m_stageDoneKeys[station].remove(m_stagePendingKey[station]); } else { m_stationPaused[station] = true; } // StartTest 自己也执行失败(后端 INTERNAL:复位 / 开机没走完等): // 必须像 RPC 层拒绝一样放开在途闸门、通知界面把按钮退回「开始测试」。 // 少了这一步,按钮会永久卡在「执行中」,再点还会被「已有未完成 StartTest」 // 吞掉 —— 现场表现就是「点了没反应,只能重启软件」。 if (isStartCommand) { // 上面的终态处理已清空 m_startCmd,这里用预先捕获的标记通知界面复位按钮。 emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, msg).trimmed()); } } qInfo().noquote() << "[backend] GetCommand" << commandId << "→" << state; }, [this, commandId](const QString &code, const QString &message) { // 后端此刻还没这条命令的记录(刚发出去就查了):保留跟踪,下一轮再问。 // 超过宽限期还是查不到,多半是命令在 RPC 层就被拒了 —— 那时才放弃。 const qint64 ageMs = QDateTime::currentMSecsSinceEpoch() - m_pendingSince.value(commandId, 0); if (code == QStringLiteral("NOT_FOUND") && ageMs < kRegisterGraceMs) { qInfo().noquote() << "[backend] GetCommand" << commandId << "暂查不到(后端尚未落记录),继续跟踪"; return; } const int station = m_pending.value(commandId, -1); forgetCommand(commandId); qInfo().noquote() << "[backend] GetCommand" << commandId << "失败:" << code << message; if (station < 0) return; if (m_startCmd[station] == commandId) { m_startCmd[station].clear(); m_startPending[station] = false; emit logLine(station, QStringLiteral("[qt] 开始测试未生效(后端查不到命令 %1:%2)") .arg(commandId, code)); emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, message).trimmed()); } else if (m_stagePendingCmd[station] == commandId) { m_stagePendingCmd[station].clear(); } // 目录查询也必须回执:否则界面上「扫描 EFI」永远是点了没反应 if (m_fileQueryCmd[station] == commandId) { m_fileQueryCmd[station].clear(); const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed(); emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg)); emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg); } }); } QString BackendLink::newCommandId(const QString &kind, int station) { // 允许字母、数字、_ . -,首字符字母/数字,≤96 字符 return QStringLiteral("qt-%1-%2-%3-%4") .arg(stationId(station)) .arg(kind) .arg(m_idToken) .arg(++m_commandSeq); } void BackendLink::setMemoryParams(int station, const QJsonObject &memoryParams) { if (station < 0 || station >= kStationCount) return; m_memoryParams[station] = memoryParams; // 新参数只影响之后的 ICT1:清掉已下发记录,让下一次 ICT1 重新下发 m_appliedCpu[station].clear(); } void BackendLink::setRmtParams(int station, const QJsonObject &rmt) { if (station < 0 || station >= kStationCount) return; // RMT 开关只在 ICT1 的 continue_uip 里用(run_rmt),改参数后下一轮才生效 m_rmtParams[station] = rmt; const bool enabled = rmt.value(QStringLiteral("enabled")).toBool(true); qInfo().noquote() << "[backend]" << stationId(station) << "RMT 参数已装载,启用 =" << (enabled ? "是(ICT1 下发 rmt enable)" : "否(ICT1 不带 rmt enable,跳过扫描)"); } void BackendLink::setAmtParams(int station, const QJsonObject &amt) { if (station < 0 || station >= kStationCount) return; // AMT 参数在 AMT 节点现场取用,这里只要存着; // 已经处理过 amt 的阶段键不清理——同一轮里不重复启动 AMT 测试, // 改参数后要生效就等下一轮(boot_id 变化时会清空阶段键)。 m_amtParams[station] = amt; const bool enabled = amt.value(QStringLiteral("enabled")).toBool(true); QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed(); if (testCommand.isEmpty()) testCommand = QStringLiteral("amemdiag 1"); qInfo().noquote() << "[backend]" << stationId(station) << "AMT 参数已装载,启用 =" << (enabled ? "是(amemdiag 1,跑完发 exit)" : "否(发 exit 跳过)") << "test_command =" << testCommand; } void BackendLink::setMtParams(int station, const QJsonObject &mt) { if (station < 0 || station >= kStationCount) return; // 和 AMT 一样:MT 参数在 UEFI Shell 节点现场取用,改参数后下一轮才生效 m_mtParams[station] = mt; const bool enabled = mt.value(QStringLiteral("enabled")).toBool(true); QString efiPath = mt.value(QStringLiteral("efi_path")).toString().trimmed(); if (efiPath.isEmpty()) efiPath = QStringLiteral("118.efi"); const QString configPath = mt.value(QStringLiteral("config_path")).toString().trimmed(); qInfo().noquote() << "[backend]" << stationId(station) << "MT 参数已装载,启用 =" << (enabled ? "是(UEFI Shell 跑 EFI)" : "否(发 skip_mt)") << "efi =" << efiPath << (configPath.isEmpty() ? QStringLiteral("(默认 mt86.cfg)") : QStringLiteral("config = %1").arg(configPath)); } // --------------------------------------------------------------------------- // BIOS UART 原文:按 (session_id, offset) 去重拼接,切行输出 // --------------------------------------------------------------------------- void BackendLink::applyBiosUart(const QJsonObject &result) { const int station = stationIndex(result.value(QStringLiteral("station_id")).toString()); const QString session = result.value(QStringLiteral("session_id")).toString(); if (station < 0 || session.isEmpty()) return; const QString sid = stationId(station); // 静音窗口到期就强制恢复:后端在一次重启前后可能沿用同一个会话编号, // 若只在 session 变化时解除静音,那一轮之后就再也看不到 BIOS 日志了。 if (m_uartMuted[station] && nowMs() - m_uartMuteMs[station] > kUartMuteMs) { m_uartMuted[station] = false; qInfo().noquote() << "[backend]" << sid << "UART 静音窗口结束,恢复显示(期间丢弃" << m_uartDropped[station] << "字节)"; m_uartDropped[station] = 0; } if (m_uartSession[station] != session) { qInfo().noquote() << "[backend]" << sid << "BIOS UART 新会话" << session; m_uartSession[station] = session; m_uartOffset[station] = 0; m_uartPending[station].clear(); m_uartLastWasCr[station] = false; m_uartMuted[station] = false; // 新会话出现:解除静音,正常显示 m_uartDropped[station] = 0; } const quint64 first = result.value(QStringLiteral("offset")).toVariant().toULongLong(); QByteArray bytes = QByteArray::fromBase64(result.value(QStringLiteral("data_base64")).toString().toLatin1()); const quint64 end = first + static_cast(bytes.size()); if (end <= m_uartOffset[station]) return; // 重连重放的已显示字节,跳过 if (first > m_uartOffset[station]) { // 首次连接回填往往从环形缓冲当前窗口起点开始(offset > 0 且本地 m_uartOffset == 0), // 属于正常回填窗口跳过已滚动淘汰的旧字节,不记误导性的缺口告警。 if (m_uartOffset[station] > 0) { qInfo().noquote() << "[backend]" << sid << "UART 字节缺口" << m_uartOffset[station] << "→" << first << ",丢弃缺口并从新偏移继续"; } m_uartPending[station].clear(); // 缺口后的残留半行不可信 m_uartLastWasCr[station] = false; m_uartOffset[station] = first; } bytes.remove(0, static_cast(m_uartOffset[station] - first)); m_uartOffset[station] = end; if (!m_uartSeen[station]) { m_uartSeen[station] = true; qInfo().noquote() << "[backend]" << sid << "首次收到 BIOS UART 字节(会话" << session << ")"; } // 诊断用:connection 报 offline 却照样在推 UART —— 说明串口转发这一路是通的, // 断的是后端到主机的电源 / 控制台状态链路。只提示一次,避免刷屏。 if (!m_connOfflineWarned[station] && m_lastConn[station] == QStringLiteral("offline")) { m_connOfflineWarned[station] = true; qInfo().noquote() << "[backend]" << sid << "注意:connection = offline,但 BIOS UART 仍在推送 —— " "串口转发链路正常,断的是后端到主机的电源 / 控制台状态链路"; } // 刚点过开始测试:旧会话的尾巴直接丢掉(游标照样前进,避免重放) if (m_uartMuted[station]) { m_uartDropped[station] += bytes.size(); return; } // 兼容 \r\n、\n 与双路 AMT 菜单仅回显 \r 的切行,并在分包截断 \r\n 时吞掉下一包首字节 \n m_uartPending[station].append(bytes); QByteArray &pending = m_uartPending[station]; int pos = 0; const int total = pending.size(); while (pos < total) { if (m_uartLastWasCr[station]) { m_uartLastWasCr[station] = false; if (pending.at(pos) == '\n') { ++pos; continue; } } int eol = -1; char eolCh = 0; for (int i = pos; i < total; ++i) { const char ch = pending.at(i); if (ch == '\r' || ch == '\n') { eol = i; eolCh = ch; break; } } if (eol < 0) break; const QByteArray line = pending.mid(pos, eol - pos); QString text = QString::fromUtf8(line); if (text.contains(QChar(0x1B))) { static const QRegularExpression ansiRe( QStringLiteral("\\x1B(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1B]*(?:\\x07|\\x1B\\\\))")); text.remove(ansiRe); text.remove(QChar(0x1B)); } emit logLine(station, text); pos = eol + 1; if (eolCh == '\r') { if (pos < total) { if (pending.at(pos) == '\n') ++pos; } else { m_uartLastWasCr[station] = true; } } } if (pos > 0) pending.remove(0, pos); }