backendlink.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. #include "backendlink.h"
  2. #include "appconfig.h"
  3. #include "localplans.h"
  4. #include "uiformat.h"
  5. #include <QCoreApplication>
  6. #include <QDateTime>
  7. #include <QDebug>
  8. #include <QDir>
  9. #include <QFile>
  10. #include <QFileInfo>
  11. #include <QJsonArray>
  12. #include <QJsonDocument>
  13. #include <QJsonObject>
  14. #include <QNetworkProxy>
  15. #include <QNetworkRequest>
  16. #include <QRegularExpression>
  17. #include <QSaveFile>
  18. #include <QUrl>
  19. #include <QUuid>
  20. namespace {
  21. const int kStationCount = 4;
  22. const int kReconnectMs = 1500; // 断线 1.5s 单次触发重连(配合状态检查防止重连风暴)
  23. const int kDisconnectDebounceMs = 2500; // 闪断 2.5s 内自动恢复时不向主界面刷断线闪烁
  24. const int kConnectTimeoutMs = 10000; // 建立连接超过 10s 无响应 → 主动断开
  25. const int kSilenceTimeoutMs = 20000; // 已连接但 20s 没有任何后端消息 → 主动断开
  26. const int kCommandPollMs = 2000; // 未结束命令的查询间隔
  27. // 命令刚发出去时后端还没落记录,此时 GetCommand 会回 NOT_FOUND。
  28. // 这两个宽限值决定「暂时查不到」要忍多久,别把还在途的命令当场判死。
  29. const qint64 kPollGraceMs = 3000; // 发出后这么久内不轮询
  30. const qint64 kRegisterGraceMs = 8000; // 这么久内的 NOT_FOUND 视为「还没到」,继续跟踪
  31. const int kUartMuteMs = 5000; // 点开始测试后丢弃旧会话尾巴的时间窗(到期强制恢复,防止永久静音)
  32. const int kBackfillPages = 8; // 连接后回填历史 UART 的页数上限(8 × 64 KB)
  33. const int kBackfillPageBytes = 65536; // ReadBiosUart 单页字节数(接口上限)
  34. const int kBackfillHoldMs = 10000; // 回填期间压住推送包的最长时间(超时强制放行,防止永久压包)
  35. QString stationId(int index) // 界面工位 0..3 → S1..S4
  36. {
  37. return QStringLiteral("S%1").arg(index + 1);
  38. }
  39. int stationIndex(const QString &id) // S1..S4 → 0..3,未知返回 -1
  40. {
  41. if (id.size() != 2 || !id.startsWith(QLatin1Char('S')))
  42. return -1;
  43. const int n = id.at(1).digitValue();
  44. return (n >= 1 && n <= kStationCount) ? n - 1 : -1;
  45. }
  46. qint64 nowMs()
  47. {
  48. return QDateTime::currentMSecsSinceEpoch();
  49. }
  50. // stage_errors 里每一项转成一句人能读的话,并提取原始 message 作为续行合并键。
  51. QString describeStageError(const QJsonValue &value, QString *rawKeyOut = nullptr)
  52. {
  53. if (rawKeyOut)
  54. rawKeyOut->clear();
  55. if (value.isString()) {
  56. const QString s = value.toString().trimmed();
  57. if (rawKeyOut)
  58. *rawKeyOut = s;
  59. return s;
  60. }
  61. if (value.isBool())
  62. return value.toBool() ? QStringLiteral("true") : QStringLiteral("false");
  63. if (value.isDouble())
  64. return QString::number(value.toDouble());
  65. if (value.isObject()) {
  66. const QJsonObject obj = value.toObject();
  67. const QString msg = obj.value(QStringLiteral("message")).toString().trimmed();
  68. if (rawKeyOut)
  69. *rawKeyOut = msg;
  70. QStringList meta;
  71. const QJsonValue cpuVal = obj.value(QStringLiteral("cpu"));
  72. const QJsonValue chVal = obj.value(QStringLiteral("channel"));
  73. bool hasCpu = false;
  74. int cpuIdx = -1;
  75. if (cpuVal.isDouble()) {
  76. cpuIdx = cpuVal.toInt(-1);
  77. hasCpu = (cpuIdx >= 0 && cpuIdx <= 1);
  78. } else if (cpuVal.isString()) {
  79. bool ok = false;
  80. const int v = cpuVal.toString().trimmed().toInt(&ok);
  81. if (ok && v >= 0 && v <= 1) {
  82. cpuIdx = v;
  83. hasCpu = true;
  84. }
  85. }
  86. QString chRaw = chVal.isString() ? chVal.toString().trimmed()
  87. : (chVal.isDouble() ? QString::number(chVal.toInt(-1)) : QString());
  88. int chIdx = -1;
  89. if (!chRaw.isEmpty()) {
  90. bool ok = false;
  91. const int v = chRaw.toInt(&ok);
  92. if (ok && v >= 0 && v < 12)
  93. chIdx = v;
  94. }
  95. if (hasCpu && chIdx >= 0) {
  96. const QChar letter = QLatin1Char('A' + chIdx);
  97. meta << QStringLiteral("CPU%1_CH%2 (CH%3)").arg(cpuIdx).arg(letter).arg(chIdx);
  98. } else if (hasCpu) {
  99. meta << QStringLiteral("CPU%1").arg(cpuIdx);
  100. } else if (!chRaw.isEmpty()) {
  101. meta << QStringLiteral("CH%1").arg(chRaw);
  102. }
  103. const QJsonValue dimmVal = obj.value(QStringLiteral("dimm"));
  104. if (dimmVal.isDouble() && dimmVal.toInt(-1) >= 0)
  105. meta << QStringLiteral("DIMM%1").arg(dimmVal.toInt());
  106. const QJsonValue rankVal = obj.value(QStringLiteral("rank"));
  107. if (rankVal.isDouble() && rankVal.toInt(-1) >= 0)
  108. meta << QStringLiteral("Rank%1").arg(rankVal.toInt());
  109. const QJsonValue bankVal = obj.value(QStringLiteral("bank"));
  110. if (bankVal.isDouble() && bankVal.toInt(-1) >= 0)
  111. meta << QStringLiteral("Bank%1").arg(bankVal.toInt());
  112. const QString addr = obj.value(QStringLiteral("address")).toString().trimmed();
  113. if (!addr.isEmpty())
  114. meta << QStringLiteral("Addr=%1").arg(addr);
  115. const QString kind = obj.value(QStringLiteral("kind")).toString().trimmed();
  116. QString head = meta.join(QStringLiteral(" · "));
  117. if (head.isEmpty() && !kind.isEmpty() && msg.isEmpty())
  118. head = kind;
  119. if (!head.isEmpty() && !msg.isEmpty())
  120. return QStringLiteral("[%1] %2").arg(head, msg);
  121. if (!msg.isEmpty())
  122. return msg;
  123. if (!head.isEmpty())
  124. return head;
  125. return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact));
  126. }
  127. if (value.isArray())
  128. return QString::fromUtf8(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact));
  129. return QString();
  130. }
  131. // X-Client-Id 的落地文件:跟 qt-plans.json / config.json 放同一个目录
  132. QString clientIdPath()
  133. {
  134. return QDir(appWritableDir()).filePath(QStringLiteral("client-id.txt"));
  135. }
  136. // 读上次用的客户端标识,没有就生成一个并写盘
  137. QString loadOrCreateClientId()
  138. {
  139. const QString path = clientIdPath();
  140. QFile in(path);
  141. if (in.open(QIODevice::ReadOnly)) {
  142. const QString saved = QString::fromUtf8(in.readAll()).trimmed();
  143. in.close();
  144. if (!saved.isEmpty())
  145. return saved;
  146. }
  147. const QString id = QStringLiteral("qt-%1").arg(
  148. QUuid::createUuid().toString(QUuid::WithoutBraces).left(8));
  149. QSaveFile out(path);
  150. if (out.open(QIODevice::WriteOnly)) {
  151. out.write(id.toUtf8());
  152. out.commit();
  153. }
  154. qInfo().noquote() << "[backend] 生成新的客户端标识" << id << "→" << path;
  155. return id;
  156. }
  157. } // namespace
  158. BackendLink::BackendLink(QObject *parent)
  159. : QObject(parent)
  160. {
  161. // command_id 必须全局唯一:同一后端会记住历史命令,重启后自增序号会撞上旧编号,
  162. // 后端会回 ALREADY_EXISTS(同编号参数不同)。这里加一个进程级时间戳后缀。
  163. m_idToken = QStringLiteral("%1").arg(QDateTime::currentMSecsSinceEpoch() % 100000000);
  164. // 手册 7.2:握手带 X-Client-Id,重连时仍算同一个客户端,测试期间不会被别的连接抢走
  165. // 工位控制权。这里把标识落盘:上位机重启后仍报同一个 id,后端才认「还是这台机器」。
  166. // 否则每次启动都是「另一客户端」,正在跑的工位连 StartTest 都发不进去
  167. // (FAILED_PRECONDITION 当前工位正由另一客户端执行测试)。
  168. m_clientId = loadOrCreateClientId();
  169. connect(&m_ws, &QWebSocket::connected, this, &BackendLink::onConnected);
  170. connect(&m_ws, &QWebSocket::disconnected, this, &BackendLink::onDisconnected);
  171. connect(&m_ws, &QWebSocket::textMessageReceived, this, &BackendLink::onTextMessage);
  172. #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
  173. connect(&m_ws, &QWebSocket::errorOccurred,
  174. #else
  175. connect(&m_ws, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
  176. #endif
  177. this, [this](QAbstractSocket::SocketError) {
  178. const QString err = m_ws.errorString();
  179. qInfo().noquote() << "[backend]" << err;
  180. if (err.contains(QStringLiteral("proxy"), Qt::CaseInsensitive))
  181. qInfo().noquote() << "[backend] 提示:连接受本机代理影响;内网后端已强制直连,"
  182. "若仍失败请核对 config.json 的 url 与系统代理设置";
  183. });
  184. m_reconnect.setSingleShot(true);
  185. m_reconnect.setInterval(kReconnectMs);
  186. connect(&m_reconnect, &QTimer::timeout, this, &BackendLink::openSocket);
  187. m_disconnectDebounce.setSingleShot(true);
  188. m_disconnectDebounce.setInterval(kDisconnectDebounceMs);
  189. connect(&m_disconnectDebounce, &QTimer::timeout, this, [this]() {
  190. if (!isConnected() && m_reportedConnected) {
  191. m_reportedConnected = false;
  192. emit connectionChanged(false);
  193. }
  194. });
  195. m_health.setInterval(1000);
  196. connect(&m_health, &QTimer::timeout, this, &BackendLink::onHealthTick);
  197. m_health.start();
  198. m_commandPoll.setInterval(kCommandPollMs);
  199. connect(&m_commandPoll, &QTimer::timeout, this, &BackendLink::pollPending);
  200. m_commandPoll.start();
  201. }
  202. BackendLink::~BackendLink()
  203. {
  204. // QWebSocket 析构时会补发一次 disconnected。那时本对象的成员(定时器、处理器表)
  205. // 正在/已经析构,onDisconnected 里再 start() 定时器就是野指针;而它 emit 出去的
  206. // connectionChanged 还会去摸主窗口已经删掉的控件 —— 关窗必崩(实测 SIGSEGV)。
  207. // 先把 socket 的信号摘干净,让析构静默进行。
  208. m_health.stop();
  209. m_reconnect.stop();
  210. m_disconnectDebounce.stop();
  211. m_commandPoll.stop();
  212. m_ws.disconnect(this);
  213. }
  214. void BackendLink::start()
  215. {
  216. // 纯净接口地址:默认按新联想一体控制主机 192.168.2.68(BMC + PXE 同机一体部署);
  217. // config.json 里加 "backend": {"url": "ws://..."} 可覆盖(本地后端就写 127.0.0.1)
  218. m_url = QStringLiteral("ws://192.168.2.68:8080/ws?view=qt-clean");
  219. const QString path = appConfigPath(QStringLiteral("config.json"));
  220. QFile f(path);
  221. if (f.open(QIODevice::ReadOnly)) {
  222. const QJsonObject root = QJsonDocument::fromJson(f.readAll()).object();
  223. const QString u = root.value(QStringLiteral("backend")).toObject()
  224. .value(QStringLiteral("url")).toString();
  225. if (!u.isEmpty())
  226. m_url = u;
  227. }
  228. // 兜底:漏了 view=qt-clean 就会连到全量接口(那套没有 StartTest,会报 UNIMPLEMENTED)
  229. if (!m_url.contains(QStringLiteral("view="))) {
  230. m_url += m_url.contains(QLatin1Char('?')) ? QStringLiteral("&view=qt-clean")
  231. : QStringLiteral("?view=qt-clean");
  232. qInfo().noquote() << "[backend] 地址未指定 view,已自动补成" << m_url;
  233. }
  234. openSocket();
  235. }
  236. void BackendLink::openSocket()
  237. {
  238. if (m_ws.state() != QAbstractSocket::UnconnectedState)
  239. return;
  240. qInfo().noquote() << "[backend] 连接" << m_url << "...";
  241. m_connectStartMs = nowMs();
  242. // 内网 / 本机后端一律直连,不让 QWebSocket 去用系统或环境变量代理。
  243. // 开发机上常设 http_proxy(本机抓包/加速代理),Qt 会把它拿去连 ws://,
  244. // 握手前就报 "The proxy type is invalid for this operation",于是每 3s 重连、
  245. // 界面一直「控制台离线」,点开始测试就提示「后端未连接,本次未下发任务」。
  246. // 后端在局域网,本来也不该经过代理;外网地址仍沿用系统默认代理。
  247. const QUrl url(m_url);
  248. const QString host = url.host();
  249. const bool direct = host.isEmpty()
  250. || host == QStringLiteral("localhost")
  251. || host == QStringLiteral("127.0.0.1")
  252. || host == QLatin1String("::1")
  253. || host.startsWith(QStringLiteral("192.168."))
  254. || host.startsWith(QStringLiteral("10."))
  255. || host.startsWith(QStringLiteral("172."));
  256. m_ws.setProxy(direct ? QNetworkProxy(QNetworkProxy::NoProxy)
  257. : QNetworkProxy(QNetworkProxy::DefaultProxy));
  258. QNetworkRequest request{QUrl(m_url)};
  259. request.setRawHeader("X-Client-Id", m_clientId.toUtf8());
  260. m_ws.open(request);
  261. }
  262. void BackendLink::onConnected()
  263. {
  264. qInfo().noquote() << "[backend] 已连上" << m_url << "client_id =" << m_clientId;
  265. m_lastMessageMs = nowMs();
  266. // 断线后不自动恢复阶段动作:手册要求连接变化时暂停本地自动下发。
  267. // 只有用户明确发起新一轮 StartTest 才解除暂停,避免重连后对旧 input_id 误操作。
  268. m_reconnect.stop();
  269. m_disconnectDebounce.stop();
  270. if (!m_reportedConnected) {
  271. m_reportedConnected = true;
  272. emit connectionChanged(true);
  273. }
  274. sendRequest(QStringLiteral("GetSystemInfo"), {}, [this](const QJsonObject &result) {
  275. const QString version = result.value(QStringLiteral("version")).toString();
  276. const QString mode = result.value(QStringLiteral("mode")).toString();
  277. qInfo().noquote() << "[backend] 后端版本" << version << "mode" << mode;
  278. const QString hint = (mode == QStringLiteral("simulated"))
  279. ? QStringLiteral("(模拟模式,不能作为实机验收证据)")
  280. : QString();
  281. emit logLine(0, QStringLiteral("[backend] 已连接后端 %1 版本 %2 %3%4")
  282. .arg(m_url, version, mode, hint));
  283. });
  284. // 把各工位当前 UART 会话的历史字节补回来:后端只在「有新字节」时推,
  285. // 程序刚起来那一刻 BIOS 往往已经没有输出,只等推送会一个字都看不到。
  286. // 走过的字节由 applyBiosUart 里的 session + offset 游标去重,不会重复显示。
  287. for (int i = 0; i < kStationCount; ++i)
  288. backfillBiosUart(i, 0, kBackfillPages);
  289. }
  290. void BackendLink::backfillBiosUart(int station, quint64 offset, int pagesLeft)
  291. {
  292. if (station < 0 || station >= kStationCount || pagesLeft <= 0)
  293. return;
  294. QJsonObject params;
  295. params.insert(QStringLiteral("station_id"), stationId(station));
  296. params.insert(QStringLiteral("offset"), QString::number(offset));
  297. params.insert(QStringLiteral("max_bytes"), kBackfillPageBytes);
  298. // 开链(offset 0)时打开压包窗口:这段时间的推送先进 m_uartDeferred,等历史补齐再放
  299. if (offset == 0)
  300. m_backfillHoldUntil[station] = nowMs() + kBackfillHoldMs;
  301. sendRequest(QStringLiteral("ReadBiosUart"), params,
  302. [this, station, offset, pagesLeft](const QJsonObject &result) {
  303. const quint64 next = result.value(QStringLiteral("next_offset")).toVariant().toULongLong();
  304. const bool hasMore = result.value(QStringLiteral("has_more")).toBool();
  305. // 和推送走同一条路:会话比对、缺口处理、按行切分、去重全在这里
  306. applyBiosUart(result);
  307. if (!hasMore) {
  308. m_backfillHoldUntil[station] = 0;
  309. flushDeferredUart(station);
  310. return;
  311. }
  312. if (next <= offset) { // 后端没前进,别死循环
  313. qInfo().noquote() << "[backend]" << stationId(station)
  314. << "UART 回填偏移未前进,停止本轮回填";
  315. m_backfillHoldUntil[station] = 0;
  316. flushDeferredUart(station);
  317. return;
  318. }
  319. if (pagesLeft <= 1) {
  320. qInfo().noquote() << "[backend]" << stationId(station)
  321. << "UART 回填达到本次上限(" << kBackfillPages * kBackfillPageBytes / 1024
  322. << "KB),余下部分随后端推送继续显示";
  323. m_backfillHoldUntil[station] = 0;
  324. flushDeferredUart(station);
  325. return;
  326. }
  327. backfillBiosUart(station, next, pagesLeft - 1);
  328. });
  329. }
  330. void BackendLink::flushDeferredUart(int station)
  331. {
  332. if (station < 0 || station >= kStationCount || m_uartDeferred[station].isEmpty())
  333. return;
  334. const QVector<QJsonObject> queued = m_uartDeferred[station];
  335. m_uartDeferred[station].clear();
  336. qInfo().noquote() << "[backend]" << stationId(station)
  337. << "UART 回填完成,补处理回填期间积压的" << queued.size() << "个推送包";
  338. for (const QJsonObject &packet : queued)
  339. applyBiosUart(packet);
  340. }
  341. void BackendLink::onDisconnected()
  342. {
  343. qInfo().noquote() << "[backend] 连接断开," << QString::number(kReconnectMs / 1000.0, 'f', 1) << "s 后重试";
  344. m_autoPaused = true; // 连接变化 → 暂停自动下发
  345. m_handlers.clear();
  346. m_errorHandlers.clear();
  347. // 旧的推送包属于上一条连接:重连后后端会重放当前会话,回填也会重新走,这里直接丢掉
  348. for (int i = 0; i < kStationCount; ++i) {
  349. m_backfillHoldUntil[i] = 0;
  350. m_uartDeferred[i].clear();
  351. // 在途 SetStageIntent 的回执可能随断线丢失,不能让 pending 永久卡住;
  352. // ready 也不能在重连后被当成当前轮次已可靠预置。
  353. m_stageIntentPending[i].clear();
  354. m_stageIntentReady[i].clear();
  355. m_startRpcInFlight[i] = false;
  356. if (!m_fileQueryCmd[i].isEmpty()) {
  357. const QString failedCmd = m_fileQueryCmd[i];
  358. m_fileQueryCmd[i].clear();
  359. forgetCommand(failedCmd);
  360. emit uefiFilesArrived(i, false, m_fileQueryPath[i], QStringList(),
  361. QStringLiteral("后端连接已断开,请重试"));
  362. }
  363. }
  364. if (m_reportedConnected && !m_disconnectDebounce.isActive())
  365. m_disconnectDebounce.start();
  366. if (!m_reconnect.isActive())
  367. m_reconnect.start();
  368. }
  369. void BackendLink::onHealthTick()
  370. {
  371. const qint64 now = nowMs();
  372. // 回填超时兜底:ReadBiosUart 没回来(后端不支持 / 丢包)也不能把推送永久压着
  373. for (int i = 0; i < kStationCount; ++i) {
  374. if (m_backfillHoldUntil[i] != 0 && now >= m_backfillHoldUntil[i]) {
  375. m_backfillHoldUntil[i] = 0;
  376. if (!m_uartDeferred[i].isEmpty()) {
  377. qInfo().noquote() << "[backend]" << stationId(i)
  378. << "UART 回填超时,先放行积压的" << m_uartDeferred[i].size() << "个推送包";
  379. flushDeferredUart(i);
  380. }
  381. }
  382. }
  383. if (m_ws.state() == QAbstractSocket::ConnectingState) {
  384. if (m_connectStartMs > 0 && now - m_connectStartMs > kConnectTimeoutMs) {
  385. qInfo().noquote() << "[backend] 连接超时," << kConnectTimeoutMs / 1000 << "s 内无响应,主动断开";
  386. m_ws.abort();
  387. }
  388. return;
  389. }
  390. if (isConnected() && m_lastMessageMs > 0 && now - m_lastMessageMs > kSilenceTimeoutMs) {
  391. qInfo().noquote() << "[backend] 连续" << kSilenceTimeoutMs / 1000 << "s 没有任何后端消息,主动断开重连";
  392. m_ws.abort();
  393. }
  394. }
  395. void BackendLink::sendRequest(const QString &method, const QJsonObject &params,
  396. const std::function<void(const QJsonObject &)> &onOk,
  397. const std::function<void(const QString &, const QString &)> &onError)
  398. {
  399. if (!isConnected()) {
  400. qInfo().noquote() << "[backend] 未连接,丢弃" << method;
  401. // 没连上也算失败:不能把调用方晾在那儿等回音
  402. if (onError)
  403. onError(QStringLiteral("OFFLINE"), QStringLiteral("未连接后端"));
  404. return;
  405. }
  406. const QString id = QStringLiteral("qt-%1").arg(++m_idCounter);
  407. if (onOk)
  408. m_handlers.insert(id, onOk);
  409. if (onError)
  410. m_errorHandlers.insert(id, onError);
  411. QJsonObject frame;
  412. frame.insert(QStringLiteral("v"), 1);
  413. frame.insert(QStringLiteral("id"), id);
  414. frame.insert(QStringLiteral("method"), method);
  415. frame.insert(QStringLiteral("params"), params);
  416. m_ws.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
  417. }
  418. void BackendLink::onTextMessage(const QString &json)
  419. {
  420. m_lastMessageMs = nowMs();
  421. const QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object();
  422. if (obj.isEmpty())
  423. return;
  424. // 推送(没有 id,先按 event 分流)
  425. const QString event = obj.value(QStringLiteral("event")).toString();
  426. if (!event.isEmpty()) {
  427. const QJsonObject result = obj.value(QStringLiteral("result")).toObject();
  428. if (event == QStringLiteral("state")) {
  429. applyState(result);
  430. } else if (event == QStringLiteral("bios_uart")) {
  431. // 回填期间先把推送压住:等 ReadBiosUart 把历史补齐再按原顺序放,
  432. // 否则推送把游标先推到很后面,回填回来的前几万字节会被当成重复整包丢掉。
  433. const int index = stationIndex(result.value(QStringLiteral("station_id")).toString());
  434. if (index >= 0 && m_backfillHoldUntil[index] > nowMs())
  435. m_uartDeferred[index].append(result);
  436. else
  437. applyBiosUart(result);
  438. } else if (event == QStringLiteral("task_complete")) {
  439. // 0.8.1.19:每轮终态主动推送。只接受当前 boot_id 的事件,避免旧轮次迟到包推进新任务。
  440. const int index = stationIndex(result.value(QStringLiteral("station_id")).toString());
  441. const QString bootId = result.value(QStringLiteral("boot_id")).toString();
  442. const QString taskStatus = result.value(QStringLiteral("task_status")).toString();
  443. const bool complete = result.value(QStringLiteral("complete")).toBool();
  444. const bool terminal = taskStatus == QStringLiteral("completed")
  445. || taskStatus == QStringLiteral("failed");
  446. if (index >= 0 && complete && terminal) {
  447. const bool eventIsOld = !m_waitingNewBoot[index] && !bootId.isEmpty()
  448. && !m_bootId[index].isEmpty() && bootId != m_bootId[index];
  449. const bool stillOldDuringRestart = m_waitingNewBoot[index]
  450. && (bootId.isEmpty()
  451. || bootId == m_bootId[index]);
  452. if (eventIsOld || stillOldDuringRestart) {
  453. qInfo().noquote() << "[backend] 忽略旧轮次 task_complete:"
  454. << stationId(index) << bootId
  455. << "当前 boot_id =" << m_bootId[index];
  456. } else {
  457. // 新轮次的 task_complete 可能先于下一帧 state 到达;boot_id 不同且正等待新轮次时,
  458. // 以该事件确认轮次切换,避免误丢真正的终态通知。
  459. if (!bootId.isEmpty() && m_waitingNewBoot[index]
  460. && bootId != m_bootId[index]) {
  461. m_bootId[index] = bootId;
  462. m_waitingNewBoot[index] = false;
  463. m_appliedCpu[index].clear();
  464. m_handledInput[index].clear();
  465. m_stageDoneKeys[index].clear();
  466. m_stagePendingCmd[index].clear();
  467. m_stagePendingKey[index].clear();
  468. m_stationPaused[index] = false;
  469. m_blockedWarned[index] = false;
  470. m_lastCompleteCmd[index].clear();
  471. m_lastTaskStatus[index].clear();
  472. m_stageErrorsJson[index].clear();
  473. m_lastVerdict[index].clear();
  474. }
  475. // 后端多 Profile 批次中间单轮完成(batch_complete=false 且未失败):
  476. // 只推快照和日志,不推进本地队列终态也不触发降温收尾。
  477. const QString verdict = result.value(QStringLiteral("verdict")).toString();
  478. const bool batchIntermediate = result.contains(QStringLiteral("batch_complete"))
  479. && !result.value(QStringLiteral("batch_complete")).toBool(true)
  480. && taskStatus != QStringLiteral("failed")
  481. && verdict != QStringLiteral("fail");
  482. // 快照事件与「队列推进」分开去重:
  483. // StageAction/GetCommand 的 complete=true 可能先到并占用
  484. // m_lastTaskCompleteBoot;不能因此吞掉后到的 verdict/stage_completions。
  485. const bool newSnapshot = bootId.isEmpty()
  486. || bootId != m_lastTaskCompleteEventBoot[index];
  487. if (newSnapshot) {
  488. if (!bootId.isEmpty() && !batchIntermediate)
  489. m_lastTaskCompleteEventBoot[index] = bootId;
  490. emit taskCompleteArrived(index, result);
  491. }
  492. // 队列终态单独去重,命令回执先到时事件只补快照、不重复推进。
  493. if (!batchIntermediate
  494. && (bootId.isEmpty() || bootId != m_lastTaskCompleteBoot[index])) {
  495. if (!bootId.isEmpty())
  496. m_lastTaskCompleteBoot[index] = bootId;
  497. m_lastTaskStatus[index] = taskStatus;
  498. emit taskProgressReported(index, true, taskStatus);
  499. }
  500. }
  501. }
  502. }
  503. return;
  504. }
  505. // 响应(按 id 匹配)
  506. const QString id = obj.value(QStringLiteral("id")).toString();
  507. const auto it = m_handlers.constFind(id);
  508. const auto itErr = m_errorHandlers.constFind(id);
  509. if (it == m_handlers.constEnd() && itErr == m_errorHandlers.constEnd())
  510. return;
  511. std::function<void(const QJsonObject &)> handler;
  512. if (it != m_handlers.constEnd()) {
  513. handler = it.value();
  514. m_handlers.erase(it);
  515. }
  516. std::function<void(const QString &, const QString &)> errorHandler;
  517. if (itErr != m_errorHandlers.constEnd()) {
  518. errorHandler = itErr.value();
  519. m_errorHandlers.erase(itErr);
  520. }
  521. if (obj.value(QStringLiteral("ok")).toBool()) {
  522. if (handler)
  523. handler(obj.value(QStringLiteral("result")).toObject());
  524. return;
  525. }
  526. const QJsonObject err = obj.value(QStringLiteral("error")).toObject();
  527. const QString code = err.value(QStringLiteral("code")).toString();
  528. const QString message = err.value(QStringLiteral("message")).toString();
  529. qInfo().noquote() << "[backend] 请求" << id << "失败:" << code << message;
  530. if (code == QStringLiteral("UNIMPLEMENTED")) {
  531. // 常见原因:连到了全量 /ws(无 view=qt-clean)或后端版本低于 0.8.1.2
  532. qInfo().noquote() << "[backend] 提示:后端不支持该方法,请确认地址带 ?view=qt-clean,"
  533. "且后端为 0.8.1.2 及以上版本";
  534. }
  535. if (errorHandler)
  536. errorHandler(code, message);
  537. }
  538. // ---------------------------------------------------------------------------
  539. // 状态推送:四工位快照 → 落库 + 本地 plan
  540. // ---------------------------------------------------------------------------
  541. // 手册 9.2:StartTest / StageAction / GetCommand 的命令结果对象新增
  542. // complete(当前任务是否到终态)与 task_status(任务状态枚举)。
  543. // complete 也可能表示「这条命令自己到终态」,所以上层只有同时看到
  544. // task_status=completed/failed 才把它当作任务终态,避免阶段动作提前推进队列。
  545. void BackendLink::reportCommandProgress(int station, const QString &commandId,
  546. const QJsonObject &result)
  547. {
  548. if (station < 0 || station >= kStationCount)
  549. return;
  550. // 字段可能在命令结果顶层,也可能嵌在 result.result 里(GetCommand 把业务结果
  551. // 放在嵌套 result 下),两处都认,兼容后端不同实现。
  552. bool complete = result.value(QStringLiteral("complete")).toBool();
  553. QString taskStatus = result.value(QStringLiteral("task_status")).toString();
  554. const QJsonObject inner = result.value(QStringLiteral("result")).toObject();
  555. if (!complete)
  556. complete = inner.value(QStringLiteral("complete")).toBool();
  557. if (taskStatus.isEmpty())
  558. taskStatus = inner.value(QStringLiteral("task_status")).toString();
  559. // complete 只有与任务终态同时出现才可推进本地队列。
  560. const bool terminalTask = taskStatus == QStringLiteral("completed")
  561. || taskStatus == QStringLiteral("failed")
  562. || taskStatus == QStringLiteral("interrupted");
  563. // task_complete 推送与 GetCommand 可能描述同一轮终态:按 boot_id 跨通道去重,
  564. // 防止先收到推送推进到下一任务后,又被迟到的 GetCommand 把下一任务误推进一次。
  565. const bool alreadyReportedForBoot = !m_bootId[station].isEmpty()
  566. && m_lastTaskCompleteBoot[station] == m_bootId[station];
  567. // 换条停机(run_state=blocked)期间不再上报 complete:命令结果包可能比 state 包先到,
  568. // 那时上层还没看到 awaiting_dimm_replacement,会误把队列推进到下一条任务。
  569. if (complete && terminalTask && !alreadyReportedForBoot
  570. && !m_blockedWarned[station] && m_lastCompleteCmd[station] != commandId) {
  571. m_lastCompleteCmd[station] = commandId;
  572. m_lastTaskStatus[station] = taskStatus;
  573. if (!m_bootId[station].isEmpty())
  574. m_lastTaskCompleteBoot[station] = m_bootId[station];
  575. emit taskProgressReported(station, true, taskStatus);
  576. } else if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) {
  577. m_lastTaskStatus[station] = taskStatus;
  578. emit taskProgressReported(station, false, taskStatus);
  579. }
  580. }
  581. // 手册 9.5:确认已更换 DIMM,清除后端换条停机挂起(awaiting_dimm_replacement)。
  582. void BackendLink::confirmDimmReplacement(int station)
  583. {
  584. if (station < 0 || station >= kStationCount)
  585. return;
  586. if (!isConnected()) {
  587. emit dimmConfirmed(station, false, QStringLiteral("后端未连接"));
  588. return;
  589. }
  590. const QString commandId = newCommandId(QStringLiteral("dimm"), station);
  591. QJsonObject params;
  592. params.insert(QStringLiteral("command_id"), commandId);
  593. params.insert(QStringLiteral("station_id"), stationId(station));
  594. // ConfirmDimmReplacement 只要求 command_id + station_id。
  595. // 该工位可能因为 blocked 被暂停自动下发,确认换条后恢复(下一轮 boot_id 也会再清一次)。
  596. m_stationPaused[station] = false;
  597. m_blockedWarned[station] = false;
  598. emit logLine(station, QStringLiteral("[qt] 提交更换异常内存条确认(%1)").arg(commandId));
  599. sendRequest(QStringLiteral("ConfirmDimmReplacement"), params,
  600. [this, station](const QJsonObject &result) {
  601. const QString state = result.value(QStringLiteral("state")).toString();
  602. if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
  603. const QJsonObject err = result.value(QStringLiteral("error")).toObject();
  604. const QString msg = QStringLiteral("%1 %2")
  605. .arg(err.value(QStringLiteral("code")).toString(),
  606. err.value(QStringLiteral("message")).toString())
  607. .trimmed();
  608. emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
  609. emit dimmConfirmed(station, false, msg);
  610. return;
  611. }
  612. emit logLine(station, QStringLiteral("[qt] 已确认更换异常内存条,后端换条停机挂起已解除"));
  613. m_stageErrorsJson[station].clear();
  614. m_lastVerdict[station].clear();
  615. emit dimmConfirmed(station, true, QString());
  616. }, [this, station](const QString &code, const QString &message) {
  617. const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed();
  618. emit logLine(station, QStringLiteral("[qt] 确认更换内存条失败:%1").arg(msg));
  619. emit dimmConfirmed(station, false, msg);
  620. });
  621. }
  622. void BackendLink::applyState(const QJsonObject &result)
  623. {
  624. const QString serverId = result.value(QStringLiteral("server_id")).toString();
  625. if (!m_serverId.isEmpty() && serverId != m_serverId) {
  626. // 后端重启:清掉旧输入节点与在途/自动运行归属,不重放任何动作,防止 canSubmitStart 永久锁死
  627. qInfo().noquote() << "[backend] server_id 变化,清理旧输入节点与在途/自动运行状态";
  628. m_autoPaused = true;
  629. for (int i = 0; i < kStationCount; ++i) {
  630. m_handledInput[i].clear();
  631. m_appliedCpu[i].clear();
  632. m_bootId[i].clear();
  633. m_lastTaskCompleteBoot[i].clear();
  634. m_lastTaskCompleteEventBoot[i].clear();
  635. m_stageDoneKeys[i].clear();
  636. m_stagePendingCmd[i].clear();
  637. m_stagePendingKey[i].clear();
  638. m_stageIntentPending[i].clear();
  639. m_stageIntentReady[i].clear();
  640. m_waitingNewBoot[i] = false;
  641. m_stationPaused[i] = false;
  642. m_blockedWarned[i] = false;
  643. m_lastCompleteCmd[i].clear();
  644. m_lastTaskStatus[i].clear();
  645. m_stageErrorsJson[i].clear();
  646. m_lastVerdict[i].clear();
  647. m_lastCanStart[i] = true;
  648. m_startRpcInFlight[i] = false;
  649. const bool hadStartPending = m_startPending[i];
  650. m_startPending[i] = false;
  651. m_startCmd[i].clear();
  652. if (!m_fileQueryCmd[i].isEmpty()) {
  653. m_fileQueryCmd[i].clear();
  654. emit uefiFilesArrived(i, false, m_fileQueryPath[i], QStringList(),
  655. QStringLiteral("后端已重启,请重试"));
  656. }
  657. if (hadStartPending)
  658. emit startTestReplied(i, false, QStringLiteral("后端实例已重启"));
  659. }
  660. m_pending.clear();
  661. m_pollCount.clear();
  662. m_pendingSince.clear();
  663. emit serverRestarted();
  664. }
  665. m_serverId = serverId;
  666. const QJsonArray stations = result.value(QStringLiteral("stations")).toArray();
  667. for (const QJsonValue &v : stations) {
  668. const QJsonObject st = v.toObject();
  669. const int index = stationIndex(st.value(QStringLiteral("station_id")).toString());
  670. if (index < 0)
  671. continue;
  672. emit stateArrived(index, st);
  673. applyStation(index, st);
  674. autoPlan(index, st);
  675. }
  676. }
  677. void BackendLink::applyStation(int station, const QJsonObject &st)
  678. {
  679. // 设备连接状态变化:没 BIOS 日志时先用它区分「后端根本没串口数据」和「Qt 端丢字节」
  680. const QString conn = st.value(QStringLiteral("connection")).toString();
  681. // 顺带记住 power / phase / run_state:控制台报 offline 时这三个值能区分
  682. // 「后端根本没连上主机」和「主机在跑、只是控制台通道断了」,日志和界面都要用
  683. m_lastPower[station] = st.value(QStringLiteral("power")).toString();
  684. m_lastPhase[station] = st.value(QStringLiteral("phase")).toString();
  685. m_lastRun[station] = st.value(QStringLiteral("run_state")).toString();
  686. m_lastCanStart[station] = st.value(QStringLiteral("can_start")).toBool(false);
  687. if (!conn.isEmpty() && conn != m_lastConn[station]) {
  688. m_lastConn[station] = conn;
  689. m_connOfflineWarned[station] = false; // 状态变过,允许再提示一次
  690. qInfo().noquote() << "[backend] 工位" << stationId(station) << "connection =" << conn
  691. << " power =" << m_lastPower[station]
  692. << " phase =" << m_lastPhase[station]
  693. << " run_state =" << m_lastRun[station];
  694. }
  695. // 当前固件输入节点:list_uefi_files 之类的手动动作要原样带回去
  696. m_lastInputId[station] = st.value(QStringLiteral("input")).toObject()
  697. .value(QStringLiteral("id")).toString();
  698. // boot_id 变化 = 新一轮启动:内存参数要在新的 ICT1 重新下发
  699. const QString bootId = st.value(QStringLiteral("boot_id")).toString();
  700. if (!bootId.isEmpty() && bootId != m_bootId[station]) {
  701. m_bootId[station] = bootId;
  702. m_appliedCpu[station].clear();
  703. m_handledInput[station].clear();
  704. m_stageDoneKeys[station].clear();
  705. m_stagePendingCmd[station].clear();
  706. m_stagePendingKey[station].clear();
  707. m_stationPaused[station] = false; // 新一轮启动,恢复自动化
  708. m_blockedWarned[station] = false; // 新一轮允许重新提示换条停机
  709. m_lastCompleteCmd[station].clear(); // 新任务允许再报一次 complete
  710. m_lastTaskCompleteBoot[station].clear();
  711. m_waitingNewBoot[station] = false;
  712. m_lastTaskStatus[station].clear();
  713. m_stageErrorsJson[station].clear(); // 新一轮允许重新报告相同内容
  714. m_lastVerdict[station].clear(); // 新一轮的 verdict 重新计
  715. }
  716. // 0.8.1.13:stage_errors 按 training / rmt / amt / mt 分类给出本轮结构化
  717. // 阶段错误与通道禁用明细。state 每秒推送一次 —— 内容没变就不重复刷日志。
  718. const QJsonObject stageErrors = st.value(QStringLiteral("stage_errors")).toObject();
  719. if (!stageErrors.isEmpty()) {
  720. const QString compact = QString::fromUtf8(
  721. QJsonDocument(stageErrors).toJson(QJsonDocument::Compact));
  722. if (compact != m_stageErrorsJson[station]) {
  723. m_stageErrorsJson[station] = compact;
  724. const char *const kStages[] = {"training", "rmt", "amt", "mt"};
  725. for (const char *stage : kStages) {
  726. const QJsonArray errors =
  727. stageErrors.value(QString::fromLatin1(stage)).toArray();
  728. if (errors.isEmpty())
  729. continue;
  730. const QString detail = QString::fromUtf8(
  731. QJsonDocument(errors).toJson(QJsonDocument::Compact));
  732. emit logLine(station, QStringLiteral("[qt] 阶段错误(%1):%2")
  733. .arg(QString::fromLatin1(stage), detail));
  734. // 同时落成一条条可读的异常记录(详情页第二个标签页)
  735. for (const QJsonValue &item : errors) {
  736. QString rawKey;
  737. const QString text = describeStageError(item, &rawKey);
  738. if (!text.isEmpty())
  739. emit alarmReported(station, QString::fromLatin1(stage), text, rawKey);
  740. }
  741. }
  742. }
  743. }
  744. // verdict 只在「刚变成 fail」的那一下记一条:state 每秒推送,不盯着变化会刷屏。
  745. // boot_id 变化时 m_lastVerdict 已清空,新一轮重新计。
  746. const QString verdict = st.value(QStringLiteral("verdict")).toString();
  747. if (!verdict.isEmpty() && verdict != m_lastVerdict[station]) {
  748. m_lastVerdict[station] = verdict;
  749. if (verdict == QStringLiteral("fail")) {
  750. const QString scope = st.value(QStringLiteral("verdict_scope")).toString();
  751. emit alarmReported(station, scope,
  752. scope.isEmpty() ? QStringLiteral("本轮判定 FAIL")
  753. : QStringLiteral("本轮判定 FAIL(%1 阶段)").arg(scope));
  754. }
  755. }
  756. // 手册 9.2:state 推送的 station.command 同样带 complete / task_status;
  757. // 工位对象自己也有 task_status,变化时才上报(每秒一包,不去重会刷屏)。
  758. const QJsonObject command = st.value(QStringLiteral("command")).toObject();
  759. if (!command.isEmpty())
  760. reportCommandProgress(station,
  761. command.value(QStringLiteral("command_id")).toString(), command);
  762. const QString taskStatus = st.value(QStringLiteral("task_status")).toString();
  763. if (!taskStatus.isEmpty() && taskStatus != m_lastTaskStatus[station]) {
  764. m_lastTaskStatus[station] = taskStatus;
  765. emit taskProgressReported(station, false, taskStatus);
  766. }
  767. // 手册 9.2/9.5:阶段 FAIL 后后端把 run_state 置为 blocked 并挂起换条,
  768. // 此时停止该工位的自动下发,等测试员换条后点「开始测试」强制重启新一轮。
  769. const QString runState = st.value(QStringLiteral("run_state")).toString();
  770. const bool awaitingDimm = st.value(QStringLiteral("awaiting_dimm_replacement")).toBool();
  771. if ((runState == QStringLiteral("blocked") || awaitingDimm) && !m_blockedWarned[station]) {
  772. m_blockedWarned[station] = true;
  773. m_stationPaused[station] = true;
  774. emit logLine(station, QStringLiteral("[qt] 后端换条停机(run_state=blocked):本阶段已跑完,"
  775. "等待更换异常内存条;换好后点「开始测试」可强制重启新一轮"));
  776. emit alarmReported(station, QString(),
  777. QStringLiteral("换条停机:等待更换异常内存条并重新开始测试"));
  778. }
  779. // FAIL / STOPPED / ABORTED 之后该工位停止自动动作,等人工处理(其他工位不受影响)
  780. if (runState == QStringLiteral("failed")
  781. || runState == QStringLiteral("stopped")
  782. || runState == QStringLiteral("interrupted")
  783. || runState == QStringLiteral("aborted")
  784. || runState == QStringLiteral("error")
  785. || runState == QStringLiteral("timeout")) {
  786. if (!m_stationPaused[station]) {
  787. qInfo().noquote() << "[backend] 工位" << stationId(station) << "进入" << runState << ",暂停该工位自动下发";
  788. m_stationPaused[station] = true;
  789. }
  790. }
  791. }
  792. // 0.8.1.19:在新的 StartTest 已受理后,将四个阶段意图提前写入后端。
  793. // 每个阶段的最后一次意图由后端 Last-Write-Wins 规则决定;成功预置后不再
  794. // 在 input.ready 时重复发送 StageAction,防止后端自动消费与前端动作撞车。
  795. void BackendLink::stageStationIntents(int station)
  796. {
  797. if (station < 0 || station >= kStationCount || !isConnected())
  798. return;
  799. m_stageIntentPending[station].clear();
  800. m_stageIntentReady[station].clear();
  801. auto sendIntent = [this, station](const QString &stage,
  802. const QString &action,
  803. const QJsonObject &extra) {
  804. m_stageIntentPending[station].insert(stage);
  805. QJsonObject params;
  806. params.insert(QStringLiteral("command_id"),
  807. newCommandId(QStringLiteral("intent-") + stage, station));
  808. params.insert(QStringLiteral("station_id"), stationId(station));
  809. params.insert(QStringLiteral("stage"), stage);
  810. params.insert(QStringLiteral("action"), action);
  811. for (auto it = extra.constBegin(); it != extra.constEnd(); ++it)
  812. params.insert(it.key(), it.value());
  813. sendRequest(QStringLiteral("SetStageIntent"), params,
  814. [this, station, stage, action](const QJsonObject &result) {
  815. m_stageIntentPending[station].remove(stage);
  816. const QString confirmation = result.value(QStringLiteral("confirmation")).toString();
  817. const QString respStage = result.value(QStringLiteral("stage")).toString();
  818. QString stageText = ui::inputStageText(stage);
  819. if (stageText == stage)
  820. stageText = stage.toUpper();
  821. if (confirmation == QStringLiteral("staged")
  822. && (respStage.isEmpty() || respStage == stage)) {
  823. m_stageIntentReady[station].insert(stage);
  824. emit logLine(station, QStringLiteral("[qt] 阶段意图已预置:%1 / %2(staged)")
  825. .arg(stageText, action));
  826. } else {
  827. // 只有明确返回 staged 且阶段匹配才能认定后端已接管;否则保留 input.ready 回退路径。
  828. m_stageIntentReady[station].remove(stage);
  829. emit logLine(station, QStringLiteral("[qt] %1 阶段未确认预置(confirmation=%2, stage=%3),到达提示符后回退普通动作")
  830. .arg(stageText,
  831. confirmation.isEmpty() ? QStringLiteral("missing") : confirmation,
  832. respStage.isEmpty() ? QStringLiteral("missing") : respStage));
  833. }
  834. }, [this, station, stage, action](const QString &code, const QString &message) {
  835. // 旧版后端不支持 SetStageIntent 时自动回退到 input.ready -> StageAction。
  836. m_stageIntentPending[station].remove(stage);
  837. m_stageIntentReady[station].remove(stage);
  838. emit logLine(station, QStringLiteral("[qt] %1 阶段预置失败(%2 %3),到达提示符后回退普通动作")
  839. .arg(stage, code, message));
  840. });
  841. };
  842. // ICT1:完整透传本地 memory_params(即使为空对象也透传以清掉上一轮残留覆写)与 rmt(含 selected/enabled),并单独指定 RMT 开关。
  843. QJsonObject ict1;
  844. const bool runRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true);
  845. ict1.insert(QStringLiteral("run_rmt"), runRmt);
  846. if (!m_rmtParams[station].isEmpty())
  847. ict1.insert(QStringLiteral("rmt"), m_rmtParams[station]);
  848. ict1.insert(QStringLiteral("memory_params"), m_memoryParams[station]);
  849. sendIntent(QStringLiteral("uip1"), QStringLiteral("continue_uip"), ict1);
  850. // AMT:按启用开关预置 start_amt / skip_amt;selected、only_tests、skip_tests 均透传。
  851. const QJsonObject amt = m_amtParams[station];
  852. const bool runAmt = amt.value(QStringLiteral("enabled")).toBool(true);
  853. QJsonObject amtExtra;
  854. amtExtra.insert(QStringLiteral("run_amt"), runAmt);
  855. if (runAmt) {
  856. QJsonObject payload;
  857. QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed();
  858. if (testCommand.isEmpty())
  859. testCommand = QStringLiteral("amemdiag 1");
  860. payload.insert(QStringLiteral("test_command"), testCommand);
  861. const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"};
  862. for (const char *key : amtKeys) {
  863. const QJsonValue value = amt.value(QLatin1String(key));
  864. if (!value.isUndefined() && !value.isNull()
  865. && (!value.isArray() || !value.toArray().isEmpty()))
  866. payload.insert(QLatin1String(key), value);
  867. }
  868. if (amt.contains(QStringLiteral("end_step")))
  869. payload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step")));
  870. amtExtra.insert(QStringLiteral("amt"), payload);
  871. }
  872. sendIntent(QStringLiteral("amt"),
  873. runAmt ? QStringLiteral("start_amt") : QStringLiteral("skip_amt"),
  874. amtExtra);
  875. // ICT2:继续固件流程,不重复应用 ICT1 参数。
  876. sendIntent(QStringLiteral("uip2"), QStringLiteral("continue_uip"), QJsonObject());
  877. // MT:后端按 mt86.cfg / PXE 规则处理文件与地址范围;这里只传本地明确配置项。
  878. const QJsonObject mt = m_mtParams[station];
  879. const bool runMt = mt.value(QStringLiteral("enabled")).toBool(true);
  880. QJsonObject mtExtra;
  881. mtExtra.insert(QStringLiteral("run_mt"), runMt);
  882. if (runMt) {
  883. const QJsonObject payload = LocalPlans::mtStagePayload(mt);
  884. if (!payload.isEmpty())
  885. mtExtra.insert(QStringLiteral("mt"), payload);
  886. }
  887. sendIntent(QStringLiteral("mt"),
  888. runMt ? QStringLiteral("start_mt") : QStringLiteral("skip_mt"),
  889. mtExtra);
  890. }
  891. void BackendLink::autoPlan(int station, const QJsonObject &st)
  892. {
  893. if (m_autoPaused || m_stationPaused[station] || m_startRpcInFlight[station])
  894. return;
  895. // 一个动作到终态才处理下一个输入节点:有在途阶段动作就先等着,
  896. // 否则会在同一个提示符上连发 CR,后端回 FAILED_PRECONDITION(输入节点已变化)
  897. if (!m_stagePendingCmd[station].isEmpty())
  898. return;
  899. const QJsonObject input = st.value(QStringLiteral("input")).toObject();
  900. if (input.isEmpty() || !input.value(QStringLiteral("ready")).toBool())
  901. return;
  902. const QString inputId = input.value(QStringLiteral("id")).toString();
  903. if (inputId.isEmpty())
  904. return;
  905. const QString stage = input.value(QStringLiteral("stage")).toString();
  906. const int cpu = input.value(QStringLiteral("cpu")).toInt(0);
  907. const bool testComplete = input.value(QStringLiteral("test_complete")).toBool();
  908. // 去重键用「阶段 + CPU」:UIP 提示符每回车一次 input.id 就变,按 id 去重会重复发
  909. QString key = QStringLiteral("%1/%2").arg(stage).arg(cpu);
  910. // 手册 3.2/3.4:AMT 跑完后菜单会再次就绪,这一次要发的是 skip_amt(exit),
  911. // 和前面的 start_amt 是两个不同动作。用独立去重键,否则会被「同阶段只处理一次」挡掉,
  912. // 结果就是一直停在 AMT 菜单、整轮测试卡死。
  913. const bool amtWanted = m_amtParams[station].value(QStringLiteral("enabled")).toBool(true);
  914. if (stage == QStringLiteral("amt") && testComplete && amtWanted)
  915. key = QStringLiteral("amt-exit/%1").arg(cpu);
  916. // SetStageIntent 已成功预置时,后端会在该阶段提示符自动消费;
  917. // AMT 跑完后后端也会按 exit_after=true 自动提交 exit,不重复发送 skip_amt。
  918. const QString intentStage = (stage == QStringLiteral("uefi"))
  919. ? QStringLiteral("mt") : stage;
  920. if (m_stageIntentPending[station].contains(intentStage)
  921. || m_stageIntentReady[station].contains(intentStage))
  922. return;
  923. if (m_stageDoneKeys[station].contains(key))
  924. return;
  925. QString action;
  926. QJsonObject extra;
  927. if (stage == QStringLiteral("uip1")) {
  928. // 每个 CPU 的 ICT1 各下发一次内存参数;同一 CPU 再次进入 ICT1 只发空回车。
  929. // 手册 3.4:ICT1 的 continue_uip 要带 run_rmt(默认 true),后端据此决定
  930. // 下发 rmt enable 跑完整 RMT 扫描,还是直接空回车跳过。
  931. action = QStringLiteral("continue_uip");
  932. const bool wantRmt = m_rmtParams[station].value(QStringLiteral("enabled")).toBool(true);
  933. extra.insert(QStringLiteral("run_rmt"), wantRmt);
  934. if (!m_rmtParams[station].isEmpty())
  935. extra.insert(QStringLiteral("rmt"), m_rmtParams[station]);
  936. if (!m_appliedCpu[station].contains(cpu) && !m_memoryParams[station].isEmpty()) {
  937. extra.insert(QStringLiteral("memory_params"), m_memoryParams[station]);
  938. m_appliedCpu[station].insert(cpu);
  939. }
  940. } else if (stage == QStringLiteral("uip2")) {
  941. action = QStringLiteral("continue_uip"); // 空参数,只发一个 CR
  942. } else if (stage == QStringLiteral("amt")) {
  943. // AMT 菜单:勾了「启用 AMT 测试」就 start_amt(手册 3.4 的极简模式:
  944. // run_amt + amt.test_command,默认 amemdiag 1),否则 skip_amt 发 exit。
  945. // 双 CPU 菜单逐个处理;input.test_complete 为真说明这颗 CPU 的 19 项算法
  946. // 已经跑出有效 PASS,此时必须由前端发 skip_amt 退出菜单。
  947. const QJsonObject amt = m_amtParams[station];
  948. if (amt.value(QStringLiteral("enabled")).toBool(true)) {
  949. if (testComplete) {
  950. action = QStringLiteral("skip_amt"); // 跑完了,退出当前 CPU 的 AMT 菜单
  951. } else {
  952. action = QStringLiteral("start_amt");
  953. extra.insert(QStringLiteral("run_amt"), true);
  954. // 只带测试命令;旧版 overrides / raw_commands 纯净接口会忽略,不再传
  955. QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed();
  956. if (testCommand.isEmpty())
  957. testCommand = QStringLiteral("amemdiag 1");
  958. QJsonObject amtPayload;
  959. amtPayload.insert(QStringLiteral("test_command"), testCommand);
  960. // 手册 9.4:后端按 amt.selected(或 only_tests / skip_tests)自动生成
  961. // 合规的 tp 表指令;end_step=0 可单步快跑全部算法。没勾就完全不传,
  962. // 由后端按默认「19 项全跑」执行,避免把空数组误读成「一项都不跑」。
  963. const char *const amtKeys[] = {"selected", "only_tests", "skip_tests"};
  964. for (const char *key : amtKeys) {
  965. const QJsonValue value = amt.value(QLatin1String(key));
  966. if (!value.isUndefined() && !value.isNull()
  967. && (!value.isArray() || !value.toArray().isEmpty()))
  968. amtPayload.insert(QLatin1String(key), value);
  969. }
  970. if (amt.contains(QStringLiteral("end_step")))
  971. amtPayload.insert(QStringLiteral("end_step"), amt.value(QStringLiteral("end_step")));
  972. extra.insert(QStringLiteral("amt"), amtPayload);
  973. }
  974. } else {
  975. action = QStringLiteral("skip_amt");
  976. }
  977. } else if (stage == QStringLiteral("uefi")) {
  978. // UEFI Shell(MT 阶段):勾了「启用 MT 测试」就 start_mt,
  979. // 后端在 Shell> 下自动 fs0: → cd EFI → 写 mt86.cfg → 118.efi;
  980. // 不勾就 skip_mt,直接按已执行阶段汇总 verdict。每颗 CPU 的 Shell 各处理一次。
  981. const QJsonObject mt = m_mtParams[station];
  982. if (mt.value(QStringLiteral("enabled")).toBool(true)) {
  983. action = QStringLiteral("start_mt");
  984. // 手册 0.8.1.13:mt 支持 efi_path / config_path / memory_range /
  985. // addr_lim_lo / addr_lim_hi / exit_mode / only_tests / skip_tests。
  986. // 只下发本地显式配置过的键;空对象则完全走后端默认。
  987. const QJsonObject mtPayload = LocalPlans::mtStagePayload(mt);
  988. if (!mtPayload.isEmpty())
  989. extra.insert(QStringLiteral("mt"), mtPayload);
  990. } else {
  991. action = QStringLiteral("skip_mt");
  992. }
  993. } else {
  994. return;
  995. }
  996. // 只发当前真正允许的动作(手册:input.actions 是此刻可用的动作)
  997. const QJsonArray allowed = input.value(QStringLiteral("actions")).toArray();
  998. if (!allowed.isEmpty()) {
  999. bool ok = false;
  1000. for (const QJsonValue &v : allowed) {
  1001. if (v.toString() == action) {
  1002. ok = true;
  1003. break;
  1004. }
  1005. }
  1006. if (!ok) {
  1007. QString stageText = ui::inputStageText(stage);
  1008. if (stageText == stage)
  1009. stageText = stage.toUpper();
  1010. qInfo().noquote() << "[backend] 工位" << stationId(station) << stageText
  1011. << "当前不允许" << action << ",等待状态变化";
  1012. return;
  1013. }
  1014. }
  1015. m_handledInput[station] = inputId;
  1016. m_stageDoneKeys[station].insert(key); // 同一阶段+CPU 只处理一次,等阶段推进
  1017. m_stagePendingKey[station] = key;
  1018. submitStageAction(station, inputId, action, extra);
  1019. }
  1020. void BackendLink::submitStageAction(int station, const QString &inputId,
  1021. const QString &action, const QJsonObject &extra)
  1022. {
  1023. const QString commandId = newCommandId(QStringLiteral("stage"), station);
  1024. QJsonObject params;
  1025. params.insert(QStringLiteral("command_id"), commandId);
  1026. params.insert(QStringLiteral("station_id"), stationId(station));
  1027. params.insert(QStringLiteral("input_id"), inputId);
  1028. params.insert(QStringLiteral("action"), action);
  1029. for (QJsonObject::const_iterator it = extra.constBegin(); it != extra.constEnd(); ++it)
  1030. params.insert(it.key(), it.value());
  1031. trackCommand(commandId, station);
  1032. m_stagePendingCmd[station] = commandId; // 在途:终态前不再发下一个节点
  1033. emit logLine(station, QStringLiteral("[qt] %1 → %2(input=%3)")
  1034. .arg(stationId(station), action, inputId.left(12)));
  1035. sendRequest(QStringLiteral("StageAction"), params, [this, commandId, station](const QJsonObject &result) {
  1036. const QString state = result.value(QStringLiteral("state")).toString();
  1037. qInfo().noquote() << "[backend] StageAction" << commandId << "state =" << state;
  1038. reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status
  1039. if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
  1040. forgetCommand(commandId);
  1041. if (m_stagePendingCmd[station] == commandId)
  1042. m_stagePendingCmd[station].clear();
  1043. const QJsonObject err = result.value(QStringLiteral("error")).toObject();
  1044. const QString code = err.value(QStringLiteral("code")).toString();
  1045. const QString msg = err.value(QStringLiteral("message")).toString();
  1046. emit logLine(station, QStringLiteral("[qt] 阶段动作 %1:%2 %3")
  1047. .arg(state, code, msg).trimmed());
  1048. if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) {
  1049. m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
  1050. } else {
  1051. m_stationPaused[station] = true;
  1052. emit logLine(station, QStringLiteral("[qt] 阶段动作 %1(已暂停该工位自动下发)").arg(state));
  1053. }
  1054. } else if (state == QStringLiteral("succeeded")) {
  1055. forgetCommand(commandId);
  1056. if (m_stagePendingCmd[station] == commandId)
  1057. m_stagePendingCmd[station].clear();
  1058. }
  1059. }, [this, commandId, station](const QString &code, const QString &message) {
  1060. forgetCommand(commandId);
  1061. if (m_stagePendingCmd[station] == commandId)
  1062. m_stagePendingCmd[station].clear();
  1063. emit logLine(station, QStringLiteral("[qt] 阶段动作被后端拒绝:%1 %2").arg(code, message).trimmed());
  1064. if (code == QStringLiteral("FAILED_PRECONDITION"))
  1065. m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
  1066. else
  1067. m_stationPaused[station] = true;
  1068. });
  1069. }
  1070. bool BackendLink::startTest(int station, bool continueTimer)
  1071. {
  1072. if (station < 0 || station >= kStationCount)
  1073. return false;
  1074. // 必须先判连接:没连上还往下走的话,请求会被 sendRequest 直接丢掉,
  1075. // m_startPending 永远为 true → 之后每次点击都被当成重复点击吞掉(表现为按钮点不动)
  1076. if (!isConnected()) {
  1077. qInfo().noquote() << "[backend] 未连接后端,忽略" << stationId(station) << "的开始测试";
  1078. emit logLine(station, QStringLiteral("[qt] 后端未连接,无法开始测试"));
  1079. return false;
  1080. }
  1081. // 记下这次点击是不是「跑着的时候点的」:界面要据此忽略复位过程中的 idle,
  1082. // 否则新一轮刚开始按钮就会闪回「开始测试」。
  1083. m_restartFromRunning[station] = (m_lastRun[station] == QStringLiteral("running")
  1084. || m_lastRun[station] == QStringLiteral("waiting_input")
  1085. || m_lastRun[station] == QStringLiteral("starting"));
  1086. // 现场口径:总览页点「开始测试 / 重新开始」就必须重新开始,不管主机当前在跑什么。
  1087. // 后端 StartTest 本身语义就是「已开机则复位、已关机则开机」,所以这里不按
  1088. // can_start 拦(那是「有没有冲突操作」的判据,测试进行中必然是 false)。
  1089. // 只在确实有冲突时留一条日志,方便事后对上是把哪一轮复位掉的。
  1090. if (!m_lastCanStart[station]) {
  1091. const QString phase = m_lastPhase[station].isEmpty() ? QStringLiteral("unknown")
  1092. : m_lastPhase[station];
  1093. const QString run = m_lastRun[station].isEmpty() ? QStringLiteral("unknown")
  1094. : m_lastRun[station];
  1095. qInfo().noquote() << "[backend]" << stationId(station)
  1096. << "can_start = false(phase =" << phase << " run_state =" << run
  1097. << "),仍提交 StartTest,由后端裁决";
  1098. emit logLine(station, QStringLiteral("[qt] 当前 %1(run_state=%2)can_start=false,"
  1099. "照常提交 StartTest,由后端裁决").arg(phase, run));
  1100. }
  1101. // connection 报 offline:不拦。后端可能只是重启后没刷新(陈旧值),
  1102. // 真正能不能做由后端在 StartTest 里重新核验,这里只留一句提示便于对日志。
  1103. if (m_lastConn[station] == QStringLiteral("offline")) {
  1104. const QString power = m_lastPower[station].isEmpty() ? QStringLiteral("unknown")
  1105. : m_lastPower[station];
  1106. const QString phase = m_lastPhase[station].isEmpty() ? QStringLiteral("unknown")
  1107. : m_lastPhase[station];
  1108. qInfo().noquote() << "[backend]" << stationId(station)
  1109. << "connection 报 offline,仍提交 StartTest,由后端重新核验"
  1110. << " power =" << power << " phase =" << phase;
  1111. emit logLine(station, QStringLiteral("[qt] 注意:后端报控制台 offline(power=%1, phase=%2),"
  1112. "照常提交开始测试,由后端核验").arg(power, phase));
  1113. }
  1114. // 同一工位已有未结束的 StartTest:拒绝重复排入(后端也会拒),直接告诉调用方
  1115. if (m_startPending[station] || m_startRpcInFlight[station]) {
  1116. qInfo().noquote() << "[backend]" << stationId(station) << "已有未完成的 StartTest"
  1117. << m_startCmd[station] << ",忽略本次点击";
  1118. emit logLine(station, QStringLiteral("[qt] 该工位已有未完成的 StartTest,忽略本次点击"));
  1119. return false;
  1120. }
  1121. const QString commandId = newCommandId(QStringLiteral("start"), station);
  1122. // 新一轮:清掉上一轮残留的输入节点与 CPU 参数下发记录
  1123. m_handledInput[station].clear();
  1124. m_appliedCpu[station].clear();
  1125. m_stageDoneKeys[station].clear();
  1126. m_stagePendingCmd[station].clear();
  1127. m_stagePendingKey[station].clear();
  1128. m_stageIntentPending[station].clear();
  1129. m_stageIntentReady[station].clear();
  1130. m_stationPaused[station] = false;
  1131. m_blockedWarned[station] = false;
  1132. m_autoPaused = false;
  1133. m_waitingNewBoot[station] = true;
  1134. // 日志区会被上层清空:短时间内丢弃旧会话的残留字节,等新会话再显示。
  1135. // 注意必须是「限时」静音:后端在一次重启前后可能沿用同一个会话编号,
  1136. // 只按 session 变化解除的话会永久静音(表现为开始测试后一条 BIOS 日志都没有)。
  1137. m_uartMuted[station] = true;
  1138. m_uartMuteMs[station] = nowMs();
  1139. m_uartDropped[station] = 0;
  1140. m_uartPending[station].clear();
  1141. m_uartLastWasCr[station] = false;
  1142. QJsonObject params;
  1143. params.insert(QStringLiteral("command_id"), commandId);
  1144. params.insert(QStringLiteral("station_id"), stationId(station));
  1145. if (continueTimer)
  1146. params.insert(QStringLiteral("continue_timer"), true);
  1147. trackCommand(commandId, station);
  1148. m_startPending[station] = true;
  1149. m_startRpcInFlight[station] = true;
  1150. m_startCmd[station] = commandId;
  1151. emit logLine(station, QStringLiteral("[qt] 已请求后端 StartTest(%1)").arg(commandId));
  1152. sendRequest(QStringLiteral("StartTest"), params, [this, station, commandId](const QJsonObject &result) {
  1153. m_startRpcInFlight[station] = false;
  1154. const QString state = result.value(QStringLiteral("state")).toString();
  1155. qInfo().noquote() << "[backend] StartTest" << commandId << "state =" << state;
  1156. reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status
  1157. if (state == QStringLiteral("queued") || state == QStringLiteral("running")
  1158. || state == QStringLiteral("dispatching")) {
  1159. // StartTest 已受理,当前旧启动已被后端接管;现在预置新一轮四阶段意图,
  1160. // 请求帧按 WebSocket 顺序先于后续阶段状态处理,不会抢写旧 BIOS 会话。
  1161. stageStationIntents(station);
  1162. emit logLine(station, QStringLiteral("[qt] StartTest 已受理(%1),等待新 BIOS 启动与可交互输入")
  1163. .arg(state));
  1164. emit startTestReplied(station, true, state);
  1165. } else if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
  1166. forgetCommand(commandId);
  1167. m_startPending[station] = false;
  1168. m_waitingNewBoot[station] = false;
  1169. if (m_startCmd[station] == commandId)
  1170. m_startCmd[station].clear();
  1171. m_stationPaused[station] = true;
  1172. const QJsonObject err = result.value(QStringLiteral("error")).toObject();
  1173. const QString code = err.value(QStringLiteral("code")).toString();
  1174. const QString msg = err.value(QStringLiteral("message")).toString();
  1175. emit logLine(station, QStringLiteral("[qt] StartTest %1:%2 %3").arg(state, code, msg));
  1176. emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, msg).trimmed());
  1177. } else if (state == QStringLiteral("succeeded")) {
  1178. forgetCommand(commandId);
  1179. const QJsonObject resObj = result.value(QStringLiteral("result")).toObject();
  1180. const QString prevBoot = resObj.value(QStringLiteral("previous_boot_id")).toString();
  1181. const QString newBoot = resObj.value(QStringLiteral("boot_id")).toString();
  1182. if (!newBoot.isEmpty() && newBoot == prevBoot) {
  1183. // 纯串口无 BMC 复位工位 StartTest 不递增 boot_id,避免 m_waitingNewBoot 吞掉本轮终态
  1184. m_waitingNewBoot[station] = false;
  1185. }
  1186. // 直接终态(复位/开机已确认并进入可交互窗口),仍先预置后续阶段意图。
  1187. stageStationIntents(station);
  1188. m_startPending[station] = false;
  1189. if (m_startCmd[station] == commandId)
  1190. m_startCmd[station].clear();
  1191. emit startTestReplied(station, true, state);
  1192. }
  1193. }, [this, station, commandId](const QString &code, const QString &message) {
  1194. m_startRpcInFlight[station] = false;
  1195. m_waitingNewBoot[station] = false;
  1196. forgetCommand(commandId);
  1197. // 后端在 RPC 层直接拒掉 StartTest(典型:FAILED_PRECONDITION,
  1198. // 该工位正被另一个客户端/网页端执行)。此时不会有任何命令记录,
  1199. // 必须在这里就把在途闸门放开、并通知界面复位按钮,
  1200. // 否则界面一直停在「执行中」,后续点击还会被「已有未完成 StartTest」吞掉。
  1201. if (m_startCmd[station] == commandId) {
  1202. m_startCmd[station].clear();
  1203. m_startPending[station] = false;
  1204. }
  1205. qInfo().noquote() << "[backend] StartTest" << commandId << "被拒绝:" << code << message;
  1206. emit logLine(station, QStringLiteral("[qt] 开始测试被后端拒绝:%1 %2").arg(code, message));
  1207. emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, message).trimmed());
  1208. });
  1209. return true;
  1210. }
  1211. namespace {
  1212. /** result.files 里每项是 {name, path, kind, size_bytes},界面只需要名字 */
  1213. QStringList uefiFileNames(const QJsonObject &result)
  1214. {
  1215. QStringList files;
  1216. const QJsonArray arr = result.value(QStringLiteral("files")).toArray();
  1217. for (const QJsonValue &v : arr) {
  1218. const QJsonObject f = v.toObject();
  1219. const QString name = f.value(QStringLiteral("name")).toString();
  1220. if (!name.isEmpty())
  1221. files << name;
  1222. }
  1223. return files;
  1224. }
  1225. /** 后端的 error 是 {code, message},转成一句能直接显示的话 */
  1226. QString rpcErrorText(const QJsonObject &result)
  1227. {
  1228. const QJsonObject err = result.value(QStringLiteral("error")).toObject();
  1229. return QStringLiteral("%1 %2")
  1230. .arg(err.value(QStringLiteral("code")).toString(),
  1231. err.value(QStringLiteral("message")).toString())
  1232. .trimmed();
  1233. }
  1234. } // namespace
  1235. void BackendLink::listUefiFiles(int station, const QString &path)
  1236. {
  1237. if (station < 0 || station >= kStationCount)
  1238. return;
  1239. if (!isConnected()) {
  1240. emit uefiFilesArrived(station, false, path, QStringList(), QStringLiteral("后端未连接"));
  1241. return;
  1242. }
  1243. if (!m_fileQueryCmd[station].isEmpty()) {
  1244. emit uefiFilesArrived(station, false, path, QStringList(),
  1245. QStringLiteral("上一次目录查询还没结束"));
  1246. return;
  1247. }
  1248. const QString commandId = newCommandId(QStringLiteral("dir"), station);
  1249. QJsonObject params;
  1250. params.insert(QStringLiteral("command_id"), commandId);
  1251. params.insert(QStringLiteral("station_id"), stationId(station));
  1252. if (!m_lastInputId[station].isEmpty())
  1253. params.insert(QStringLiteral("input_id"), m_lastInputId[station]);
  1254. params.insert(QStringLiteral("action"), QStringLiteral("list_uefi_files"));
  1255. params.insert(QStringLiteral("path"), path);
  1256. m_fileQueryCmd[station] = commandId;
  1257. m_fileQueryPath[station] = path;
  1258. trackCommand(commandId, station);
  1259. emit logLine(station, QStringLiteral("[qt] 查询 UEFI 目录 %1(%2)").arg(path, commandId));
  1260. sendRequest(QStringLiteral("StageAction"), params,
  1261. [this, station, commandId](const QJsonObject &result) {
  1262. const QString state = result.value(QStringLiteral("state")).toString();
  1263. qInfo().noquote() << "[backend] list_uefi_files" << commandId << "state =" << state;
  1264. // 后端也可能直接同步跑完(缓存命中),那就当场给结果,不必等轮询
  1265. if (state == QStringLiteral("succeeded")) {
  1266. if (m_fileQueryCmd[station] == commandId) {
  1267. forgetCommand(commandId);
  1268. m_fileQueryCmd[station].clear();
  1269. emit uefiFilesArrived(station, true, m_fileQueryPath[station],
  1270. uefiFileNames(result), QString());
  1271. }
  1272. return;
  1273. }
  1274. if (state == QStringLiteral("failed") || state == QStringLiteral("interrupted")) {
  1275. if (m_fileQueryCmd[station] == commandId) {
  1276. forgetCommand(commandId);
  1277. m_fileQueryCmd[station].clear();
  1278. const QString msg = rpcErrorText(result);
  1279. emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg));
  1280. emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg);
  1281. }
  1282. }
  1283. }, [this, station, commandId](const QString &code, const QString &message) {
  1284. if (m_fileQueryCmd[station] != commandId)
  1285. return; // 已被别的路径处理过,别重复弹窗
  1286. forgetCommand(commandId);
  1287. m_fileQueryCmd[station].clear();
  1288. const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed();
  1289. emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg));
  1290. emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg);
  1291. });
  1292. }
  1293. void BackendLink::trackCommand(const QString &commandId, int station)
  1294. {
  1295. m_pending.insert(commandId, station);
  1296. m_pollCount.insert(commandId, 0);
  1297. m_pendingSince.insert(commandId, QDateTime::currentMSecsSinceEpoch());
  1298. }
  1299. void BackendLink::forgetCommand(const QString &commandId)
  1300. {
  1301. m_pending.remove(commandId);
  1302. m_pollCount.remove(commandId);
  1303. m_pendingSince.remove(commandId);
  1304. }
  1305. void BackendLink::pollPending()
  1306. {
  1307. if (!isConnected())
  1308. return;
  1309. const qint64 now = QDateTime::currentMSecsSinceEpoch();
  1310. const QStringList ids = m_pending.keys();
  1311. for (const QString &commandId : ids) {
  1312. // 刚发出去的命令后端还没落记录,这时候问 GetCommand 只会拿到 NOT_FOUND。
  1313. // 以前就在这里被误判成失败、直接停止跟踪,于是命令真正的结果永远回不来
  1314. // (界面表现:点了「扫描 EFI」没有任何反应)。
  1315. if (now - m_pendingSince.value(commandId, 0) < kPollGraceMs)
  1316. continue;
  1317. const int n = m_pollCount.value(commandId, 0) + 1;
  1318. m_pollCount.insert(commandId, n);
  1319. if (n > 15) { // 约 30s 仍拿不到记录:多为后端没接受该命令,停止轮询
  1320. const int station = m_pending.value(commandId, -1);
  1321. forgetCommand(commandId);
  1322. if (station >= 0) {
  1323. // 在途闸门要放开,否则该工位会一直卡着不再自动下发
  1324. if (m_stagePendingCmd[station] == commandId)
  1325. m_stagePendingCmd[station].clear();
  1326. // StartTest 也一样:后端查不到这条记录时必须放开,
  1327. // 否则 m_startPending 永远为 true,之后每次点击「开始测试」都被吞掉
  1328. if (m_startCmd[station] == commandId) {
  1329. m_startCmd[station].clear();
  1330. m_startPending[station] = false;
  1331. emit startTestReplied(station, false, QStringLiteral("命令 %1 查询不到记录").arg(commandId));
  1332. }
  1333. if (m_fileQueryCmd[station] == commandId) {
  1334. m_fileQueryCmd[station].clear();
  1335. emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(),
  1336. QStringLiteral("命令 %1 查询不到记录").arg(commandId));
  1337. }
  1338. emit logLine(station, QStringLiteral("[qt] 命令 %1 查询不到记录,已停止跟踪").arg(commandId));
  1339. }
  1340. continue;
  1341. }
  1342. pollCommand(commandId);
  1343. }
  1344. }
  1345. void BackendLink::pollCommand(const QString &commandId)
  1346. {
  1347. QJsonObject params;
  1348. params.insert(QStringLiteral("command_id"), commandId);
  1349. sendRequest(QStringLiteral("GetCommand"), params, [this, commandId](const QJsonObject &result) {
  1350. const QString state = result.value(QStringLiteral("state")).toString();
  1351. const int station = m_pending.value(commandId, -1);
  1352. reportCommandProgress(station, commandId, result); // 手册 9.2:complete / task_status
  1353. const bool terminal = (state == QStringLiteral("succeeded")
  1354. || state == QStringLiteral("failed")
  1355. || state == QStringLiteral("interrupted"));
  1356. const bool isStartCommand = station >= 0 && m_startCmd[station] == commandId;
  1357. if (terminal) {
  1358. forgetCommand(commandId);
  1359. if (isStartCommand) {
  1360. m_startCmd[station].clear();
  1361. m_startPending[station] = false; // 放开工位,允许再次点「开始测试」
  1362. } else if (station >= 0 && m_stagePendingCmd[station] == commandId) {
  1363. m_stagePendingCmd[station].clear();// 阶段动作结束,可以处理下一个节点
  1364. }
  1365. // 目录浏览(0.8.1.14 list_uefi_files):结果在 result.files
  1366. if (station >= 0 && m_fileQueryCmd[station] == commandId) {
  1367. m_fileQueryCmd[station].clear();
  1368. const QString path = m_fileQueryPath[station];
  1369. if (state == QStringLiteral("succeeded"))
  1370. emit uefiFilesArrived(station, true, path, uefiFileNames(result), QString());
  1371. else
  1372. emit uefiFilesArrived(station, false, path, QStringList(), rpcErrorText(result));
  1373. }
  1374. }
  1375. if (station >= 0 && (state == QStringLiteral("failed")
  1376. || state == QStringLiteral("interrupted"))) {
  1377. const QJsonObject err = result.value(QStringLiteral("error")).toObject();
  1378. const QString code = err.value(QStringLiteral("code")).toString();
  1379. const QString msg = err.value(QStringLiteral("message")).toString();
  1380. emit logLine(station, QStringLiteral("[qt] 命令 %1 %2:%3 %4")
  1381. .arg(commandId, state == QStringLiteral("interrupted")
  1382. ? QStringLiteral("中断") : QStringLiteral("失败"), code, msg));
  1383. // 输入节点已变化:撤回该节点的「已完成」标记,等新状态用新 input.id 重试;
  1384. // 其他错误(链路不可用 / 后端 INTERNAL 等)才真正暂停该工位。
  1385. if (state == QStringLiteral("failed") && code == QStringLiteral("FAILED_PRECONDITION")) {
  1386. m_stageDoneKeys[station].remove(m_stagePendingKey[station]);
  1387. } else {
  1388. m_stationPaused[station] = true;
  1389. }
  1390. // StartTest 自己也执行失败(后端 INTERNAL:复位 / 开机没走完等):
  1391. // 必须像 RPC 层拒绝一样放开在途闸门、通知界面把按钮退回「开始测试」。
  1392. // 少了这一步,按钮会永久卡在「执行中」,再点还会被「已有未完成 StartTest」
  1393. // 吞掉 —— 现场表现就是「点了没反应,只能重启软件」。
  1394. if (isStartCommand) {
  1395. // 上面的终态处理已清空 m_startCmd,这里用预先捕获的标记通知界面复位按钮。
  1396. emit startTestReplied(station, false,
  1397. QStringLiteral("%1 %2").arg(code, msg).trimmed());
  1398. }
  1399. }
  1400. qInfo().noquote() << "[backend] GetCommand" << commandId << "→" << state;
  1401. }, [this, commandId](const QString &code, const QString &message) {
  1402. // 后端此刻还没这条命令的记录(刚发出去就查了):保留跟踪,下一轮再问。
  1403. // 超过宽限期还是查不到,多半是命令在 RPC 层就被拒了 —— 那时才放弃。
  1404. const qint64 ageMs = QDateTime::currentMSecsSinceEpoch()
  1405. - m_pendingSince.value(commandId, 0);
  1406. if (code == QStringLiteral("NOT_FOUND") && ageMs < kRegisterGraceMs) {
  1407. qInfo().noquote() << "[backend] GetCommand" << commandId
  1408. << "暂查不到(后端尚未落记录),继续跟踪";
  1409. return;
  1410. }
  1411. const int station = m_pending.value(commandId, -1);
  1412. forgetCommand(commandId);
  1413. qInfo().noquote() << "[backend] GetCommand" << commandId << "失败:" << code << message;
  1414. if (station < 0)
  1415. return;
  1416. if (m_startCmd[station] == commandId) {
  1417. m_startCmd[station].clear();
  1418. m_startPending[station] = false;
  1419. emit logLine(station, QStringLiteral("[qt] 开始测试未生效(后端查不到命令 %1:%2)")
  1420. .arg(commandId, code));
  1421. emit startTestReplied(station, false, QStringLiteral("%1 %2").arg(code, message).trimmed());
  1422. } else if (m_stagePendingCmd[station] == commandId) {
  1423. m_stagePendingCmd[station].clear();
  1424. }
  1425. // 目录查询也必须回执:否则界面上「扫描 EFI」永远是点了没反应
  1426. if (m_fileQueryCmd[station] == commandId) {
  1427. m_fileQueryCmd[station].clear();
  1428. const QString msg = QStringLiteral("%1 %2").arg(code, message).trimmed();
  1429. emit logLine(station, QStringLiteral("[qt] UEFI 目录查询失败:%1").arg(msg));
  1430. emit uefiFilesArrived(station, false, m_fileQueryPath[station], QStringList(), msg);
  1431. }
  1432. });
  1433. }
  1434. QString BackendLink::newCommandId(const QString &kind, int station)
  1435. {
  1436. // 允许字母、数字、_ . -,首字符字母/数字,≤96 字符
  1437. return QStringLiteral("qt-%1-%2-%3-%4")
  1438. .arg(stationId(station))
  1439. .arg(kind)
  1440. .arg(m_idToken)
  1441. .arg(++m_commandSeq);
  1442. }
  1443. void BackendLink::setMemoryParams(int station, const QJsonObject &memoryParams)
  1444. {
  1445. if (station < 0 || station >= kStationCount)
  1446. return;
  1447. m_memoryParams[station] = memoryParams;
  1448. // 新参数只影响之后的 ICT1:清掉已下发记录,让下一次 ICT1 重新下发
  1449. m_appliedCpu[station].clear();
  1450. }
  1451. void BackendLink::setRmtParams(int station, const QJsonObject &rmt)
  1452. {
  1453. if (station < 0 || station >= kStationCount)
  1454. return;
  1455. // RMT 开关只在 ICT1 的 continue_uip 里用(run_rmt),改参数后下一轮才生效
  1456. m_rmtParams[station] = rmt;
  1457. const bool enabled = rmt.value(QStringLiteral("enabled")).toBool(true);
  1458. qInfo().noquote() << "[backend]" << stationId(station)
  1459. << "RMT 参数已装载,启用 =" << (enabled ? "是(ICT1 下发 rmt enable)"
  1460. : "否(ICT1 不带 rmt enable,跳过扫描)");
  1461. }
  1462. void BackendLink::setAmtParams(int station, const QJsonObject &amt)
  1463. {
  1464. if (station < 0 || station >= kStationCount)
  1465. return;
  1466. // AMT 参数在 AMT 节点现场取用,这里只要存着;
  1467. // 已经处理过 amt 的阶段键不清理——同一轮里不重复启动 AMT 测试,
  1468. // 改参数后要生效就等下一轮(boot_id 变化时会清空阶段键)。
  1469. m_amtParams[station] = amt;
  1470. const bool enabled = amt.value(QStringLiteral("enabled")).toBool(true);
  1471. QString testCommand = amt.value(QStringLiteral("test_command")).toString().trimmed();
  1472. if (testCommand.isEmpty())
  1473. testCommand = QStringLiteral("amemdiag 1");
  1474. qInfo().noquote() << "[backend]" << stationId(station)
  1475. << "AMT 参数已装载,启用 =" << (enabled ? "是(amemdiag 1,跑完发 exit)"
  1476. : "否(发 exit 跳过)")
  1477. << "test_command =" << testCommand;
  1478. }
  1479. void BackendLink::setMtParams(int station, const QJsonObject &mt)
  1480. {
  1481. if (station < 0 || station >= kStationCount)
  1482. return;
  1483. // 和 AMT 一样:MT 参数在 UEFI Shell 节点现场取用,改参数后下一轮才生效
  1484. m_mtParams[station] = mt;
  1485. const bool enabled = mt.value(QStringLiteral("enabled")).toBool(true);
  1486. QString efiPath = mt.value(QStringLiteral("efi_path")).toString().trimmed();
  1487. if (efiPath.isEmpty())
  1488. efiPath = QStringLiteral("118.efi");
  1489. const QString configPath = mt.value(QStringLiteral("config_path")).toString().trimmed();
  1490. qInfo().noquote() << "[backend]" << stationId(station)
  1491. << "MT 参数已装载,启用 =" << (enabled ? "是(UEFI Shell 跑 EFI)" : "否(发 skip_mt)")
  1492. << "efi =" << efiPath
  1493. << (configPath.isEmpty() ? QStringLiteral("(默认 mt86.cfg)")
  1494. : QStringLiteral("config = %1").arg(configPath));
  1495. }
  1496. // ---------------------------------------------------------------------------
  1497. // BIOS UART 原文:按 (session_id, offset) 去重拼接,切行输出
  1498. // ---------------------------------------------------------------------------
  1499. void BackendLink::applyBiosUart(const QJsonObject &result)
  1500. {
  1501. const int station = stationIndex(result.value(QStringLiteral("station_id")).toString());
  1502. const QString session = result.value(QStringLiteral("session_id")).toString();
  1503. if (station < 0 || session.isEmpty())
  1504. return;
  1505. const QString sid = stationId(station);
  1506. // 静音窗口到期就强制恢复:后端在一次重启前后可能沿用同一个会话编号,
  1507. // 若只在 session 变化时解除静音,那一轮之后就再也看不到 BIOS 日志了。
  1508. if (m_uartMuted[station] && nowMs() - m_uartMuteMs[station] > kUartMuteMs) {
  1509. m_uartMuted[station] = false;
  1510. qInfo().noquote() << "[backend]" << sid << "UART 静音窗口结束,恢复显示(期间丢弃"
  1511. << m_uartDropped[station] << "字节)";
  1512. m_uartDropped[station] = 0;
  1513. }
  1514. if (m_uartSession[station] != session) {
  1515. qInfo().noquote() << "[backend]" << sid << "BIOS UART 新会话" << session;
  1516. m_uartSession[station] = session;
  1517. m_uartOffset[station] = 0;
  1518. m_uartPending[station].clear();
  1519. m_uartLastWasCr[station] = false;
  1520. m_uartMuted[station] = false; // 新会话出现:解除静音,正常显示
  1521. m_uartDropped[station] = 0;
  1522. }
  1523. const quint64 first = result.value(QStringLiteral("offset")).toVariant().toULongLong();
  1524. QByteArray bytes = QByteArray::fromBase64(result.value(QStringLiteral("data_base64")).toString().toLatin1());
  1525. const quint64 end = first + static_cast<quint64>(bytes.size());
  1526. if (end <= m_uartOffset[station])
  1527. return; // 重连重放的已显示字节,跳过
  1528. if (first > m_uartOffset[station]) {
  1529. // 首次连接回填往往从环形缓冲当前窗口起点开始(offset > 0 且本地 m_uartOffset == 0),
  1530. // 属于正常回填窗口跳过已滚动淘汰的旧字节,不记误导性的缺口告警。
  1531. if (m_uartOffset[station] > 0) {
  1532. qInfo().noquote() << "[backend]" << sid << "UART 字节缺口" << m_uartOffset[station]
  1533. << "→" << first << ",丢弃缺口并从新偏移继续";
  1534. }
  1535. m_uartPending[station].clear(); // 缺口后的残留半行不可信
  1536. m_uartLastWasCr[station] = false;
  1537. m_uartOffset[station] = first;
  1538. }
  1539. bytes.remove(0, static_cast<int>(m_uartOffset[station] - first));
  1540. m_uartOffset[station] = end;
  1541. if (!m_uartSeen[station]) {
  1542. m_uartSeen[station] = true;
  1543. qInfo().noquote() << "[backend]" << sid << "首次收到 BIOS UART 字节(会话" << session << ")";
  1544. }
  1545. // 诊断用:connection 报 offline 却照样在推 UART —— 说明串口转发这一路是通的,
  1546. // 断的是后端到主机的电源 / 控制台状态链路。只提示一次,避免刷屏。
  1547. if (!m_connOfflineWarned[station] && m_lastConn[station] == QStringLiteral("offline")) {
  1548. m_connOfflineWarned[station] = true;
  1549. qInfo().noquote() << "[backend]" << sid
  1550. << "注意:connection = offline,但 BIOS UART 仍在推送 —— "
  1551. "串口转发链路正常,断的是后端到主机的电源 / 控制台状态链路";
  1552. }
  1553. // 刚点过开始测试:旧会话的尾巴直接丢掉(游标照样前进,避免重放)
  1554. if (m_uartMuted[station]) {
  1555. m_uartDropped[station] += bytes.size();
  1556. return;
  1557. }
  1558. // 兼容 \r\n、\n 与双路 AMT 菜单仅回显 \r 的切行,并在分包截断 \r\n 时吞掉下一包首字节 \n
  1559. m_uartPending[station].append(bytes);
  1560. QByteArray &pending = m_uartPending[station];
  1561. int pos = 0;
  1562. const int total = pending.size();
  1563. while (pos < total) {
  1564. if (m_uartLastWasCr[station]) {
  1565. m_uartLastWasCr[station] = false;
  1566. if (pending.at(pos) == '\n') {
  1567. ++pos;
  1568. continue;
  1569. }
  1570. }
  1571. int eol = -1;
  1572. char eolCh = 0;
  1573. for (int i = pos; i < total; ++i) {
  1574. const char ch = pending.at(i);
  1575. if (ch == '\r' || ch == '\n') {
  1576. eol = i;
  1577. eolCh = ch;
  1578. break;
  1579. }
  1580. }
  1581. if (eol < 0)
  1582. break;
  1583. const QByteArray line = pending.mid(pos, eol - pos);
  1584. QString text = QString::fromUtf8(line);
  1585. if (text.contains(QChar(0x1B))) {
  1586. static const QRegularExpression ansiRe(
  1587. QStringLiteral("\\x1B(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1B]*(?:\\x07|\\x1B\\\\))"));
  1588. text.remove(ansiRe);
  1589. text.remove(QChar(0x1B));
  1590. }
  1591. emit logLine(station, text);
  1592. pos = eol + 1;
  1593. if (eolCh == '\r') {
  1594. if (pos < total) {
  1595. if (pending.at(pos) == '\n')
  1596. ++pos;
  1597. } else {
  1598. m_uartLastWasCr[station] = true;
  1599. }
  1600. }
  1601. }
  1602. if (pos > 0)
  1603. pending.remove(0, pos);
  1604. }