board-logic.test.mjs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. import test from "node:test";
  2. import assert from "node:assert/strict";
  3. import {createHash} from "node:crypto";
  4. import {existsSync, readFileSync} from "node:fs";
  5. import {fileURLToPath} from "node:url";
  6. import {
  7. BACK_MIRROR_AXIS,
  8. buildBoardIndex,
  9. buildPeripheralIndex,
  10. connectorPinGroups,
  11. displayBounds,
  12. displayPoint,
  13. extractPathResistors,
  14. filterPeripheralCatalog,
  15. findCandidates,
  16. generateAdcSnippet,
  17. identityMatch,
  18. isValidRtlPortName,
  19. itemVisibleOnSide,
  20. mirrorBoardX,
  21. parseBoardQuery,
  22. resolveExactNetName,
  23. resolveLogicalPin,
  24. sameNetMembers,
  25. sameNetPins,
  26. searchBoard,
  27. } from "../../tools/board-viewer/web/board-logic.mjs";
  28. function resolveGeneratedAsset(name) {
  29. // Live repo: tools/board-viewer/generated; compact package: evidence/board-viewer.
  30. const candidates = [
  31. new URL(`../../tools/board-viewer/generated/${name}`, import.meta.url),
  32. new URL(`../../evidence/board-viewer/${name}`, import.meta.url),
  33. new URL(`../evidence/board-viewer/${name}`, import.meta.url),
  34. ];
  35. for (const url of candidates) {
  36. const path = fileURLToPath(url);
  37. if (existsSync(path)) {
  38. return url;
  39. }
  40. }
  41. return candidates[0];
  42. }
  43. function pin(overrides = {}) {
  44. return {
  45. id: "fixture-pin",
  46. number: "1",
  47. pad_role: "contact",
  48. net: "UART_A_TX",
  49. summary: "UART transmit",
  50. path: ["CON10.1", "UART_A_TX", "FPGA A1"],
  51. mechanical: false,
  52. electrical: true,
  53. direction: "output",
  54. external_level: "3.3V LVCMOS",
  55. function_category: "uart_tx",
  56. reserved: false,
  57. fixed_load_conflict: false,
  58. board_pull: null,
  59. adc_pulltype: null,
  60. programming: {
  61. status: "verified_fpga",
  62. conclusion: "FPGA 输出 UART_A_TX",
  63. network_explanation: "连接器网络 UART_A_TX 直达 FPGA",
  64. hdl_guidance: "RTL 端口方向应为 output",
  65. connection_guidance: ["连接到对端设备的接收端(RX)。"],
  66. constraints: ["LOCATION = A1", "IOSTANDARD = LVCMOS33"],
  67. risks: ["仍需检查当前工程约束冲突。"],
  68. evidence_tier: "cross_verified",
  69. sources: ["fixture"],
  70. },
  71. evidence_tier: "cross_verified",
  72. fpga: {
  73. ball: "A1",
  74. board_signal: "UART_A_TX",
  75. io_standard: "LVCMOS33",
  76. capabilities: ["gpio", "uart_tx"],
  77. evidence_tier: "cross_verified",
  78. sources: ["fixture"],
  79. },
  80. recommendation: {eligible: true, reasons: []},
  81. ...overrides,
  82. };
  83. }
  84. function resistor(overrides = {}) {
  85. return {
  86. reference: "R12",
  87. category: "R",
  88. component_value: "22R",
  89. value_ohms: 22,
  90. value_tokens: ["22r", "22", "22ohm"],
  91. summary: "电阻 22R · NET_A↔NET_B",
  92. position: {x: 1, y: 1},
  93. view_position: {x: 1, y: 1},
  94. rotation: 0,
  95. bounds: {x: 0, y: 0, width: 1, height: 1},
  96. view_bounds: {x: 0, y: 0, width: 1, height: 1},
  97. side: "front",
  98. pads: [
  99. {
  100. number: "1",
  101. net: "NET_A",
  102. position: {x: 0, y: 0},
  103. view_position: {x: 0, y: 0},
  104. pad_role: "electrical",
  105. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  106. },
  107. {
  108. number: "2",
  109. net: "NET_B",
  110. position: {x: 1, y: 0},
  111. view_position: {x: 1, y: 0},
  112. pad_role: "electrical",
  113. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  114. },
  115. ],
  116. ...overrides,
  117. };
  118. }
  119. function boardData() {
  120. return {
  121. resistors: [
  122. resistor(),
  123. resistor({
  124. reference: "R1225",
  125. component_value: "10k",
  126. value_ohms: 10000,
  127. value_tokens: ["10k", "10000", "10000r"],
  128. pads: [
  129. {
  130. number: "1",
  131. net: "OTHER",
  132. position: {x: 2, y: 0},
  133. view_position: {x: 2, y: 0},
  134. pad_role: "electrical",
  135. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  136. },
  137. {
  138. number: "2",
  139. net: "OTHER2",
  140. position: {x: 3, y: 0},
  141. view_position: {x: 3, y: 0},
  142. pad_role: "electrical",
  143. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  144. },
  145. ],
  146. }),
  147. resistor({
  148. reference: "R7",
  149. component_value: "4.7k",
  150. value_ohms: 4700,
  151. value_tokens: ["4.7k", "4k7", "4700", "4700r"],
  152. pads: [
  153. {
  154. number: "1",
  155. net: "PUL1",
  156. position: {x: 4, y: 0},
  157. view_position: {x: 4, y: 0},
  158. pad_role: "electrical",
  159. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  160. },
  161. {
  162. number: "2",
  163. net: "GND",
  164. position: {x: 5, y: 0},
  165. view_position: {x: 5, y: 0},
  166. pad_role: "electrical",
  167. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  168. },
  169. ],
  170. }),
  171. resistor({
  172. reference: "R674",
  173. component_value: "",
  174. value_ohms: null,
  175. value_tokens: [],
  176. pads: [
  177. {
  178. number: "1",
  179. net: "BANK0_GPIO15",
  180. position: {x: 6, y: 0},
  181. view_position: {x: 6, y: 0},
  182. pad_role: "electrical",
  183. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  184. },
  185. {
  186. number: "2",
  187. net: "PUL1",
  188. position: {x: 7, y: 0},
  189. view_position: {x: 7, y: 0},
  190. pad_role: "electrical",
  191. size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0},
  192. },
  193. ],
  194. }),
  195. ],
  196. touchpoints: [
  197. {
  198. reference: "CON78",
  199. category: "CON",
  200. summary: "UART2 RS-232 connector through U23",
  201. pins: [
  202. pin({
  203. number: "1",
  204. net: "RS232_TX2",
  205. path: ["CON78.1 RS232_TX2", "U23", "UART2_TX", "FPGA M10"],
  206. external_level: "RS232",
  207. reserved: true,
  208. fpga: {
  209. ball: "M10",
  210. board_signal: "UART2_TX",
  211. io_standard: "LVCMOS33",
  212. capabilities: ["gpio", "uart_tx", "rs232_via_transceiver"],
  213. evidence_tier: "cross_verified",
  214. sources: ["fixture"],
  215. },
  216. recommendation: {eligible: false, reasons: ["reserved"]},
  217. programming: {
  218. status: "verified_fpga",
  219. conclusion: "FPGA 输出 UART2_TX 经 U23 转为 RS-232",
  220. network_explanation: "连接器侧网络 RS232_TX2 对应逻辑侧 UART2_TX",
  221. hdl_guidance: "RTL 端口方向应为 output",
  222. connection_guidance: ["连接到对端设备的接收端(RX)。", "不能直接接 3.3V TTL/CMOS 串口。"],
  223. constraints: ["LOCATION = M10", "IOSTANDARD = LVCMOS33"],
  224. risks: ["当前功能已保留。"],
  225. evidence_tier: "cross_verified",
  226. sources: ["fixture"],
  227. },
  228. }),
  229. ],
  230. },
  231. {
  232. reference: "CON10",
  233. category: "CON",
  234. summary: "Verified UART fixture",
  235. pins: [pin()],
  236. },
  237. {
  238. reference: "J2",
  239. category: "J",
  240. summary: "PWM fixture",
  241. pins: [
  242. pin({
  243. number: "7",
  244. net: "FAN_PWM_TEST",
  245. summary: "Fan PWM",
  246. function_category: "pwm",
  247. board_pull: "10k external pull-up to 3.3V",
  248. fpga: {
  249. ball: "B2",
  250. board_signal: "FAN_PWM_TEST",
  251. io_standard: "LVCMOS33",
  252. capabilities: ["gpio", "gpio_output", "pwm"],
  253. evidence_tier: "cross_verified",
  254. sources: ["fixture"],
  255. },
  256. }),
  257. pin({
  258. number: "8",
  259. net: "FAN_PWM_PULLTYPE",
  260. function_category: "pwm",
  261. adc_pulltype: "PULLUP",
  262. fpga: {
  263. ball: "B3",
  264. board_signal: "FAN_PWM_PULLTYPE",
  265. io_standard: "LVCMOS33",
  266. capabilities: ["gpio", "gpio_output", "pwm"],
  267. evidence_tier: "cross_verified",
  268. sources: ["fixture"],
  269. },
  270. }),
  271. ],
  272. },
  273. {
  274. reference: "TP3",
  275. category: "TP",
  276. summary: "Unverified test point",
  277. pins: [
  278. pin({
  279. net: "MYSTERY",
  280. external_level: "unknown",
  281. evidence_tier: "unknown",
  282. fpga: null,
  283. recommendation: {eligible: false, reasons: ["pin_evidence_not_verified"]},
  284. }),
  285. ],
  286. },
  287. ],
  288. };
  289. }
  290. test("search covers reference, pin, net, function, capability, and FPGA ball", () => {
  291. const data = boardData();
  292. assert.equal(searchBoard(data, "CON78")[0].reference, "CON78");
  293. assert.equal(searchBoard(data, "CON78.1")[0].pinNumber, "1");
  294. assert.equal(searchBoard(data, "rs232_tx2")[0].reference, "CON78");
  295. assert.equal(searchBoard(data, "uart_tx")[0].reference, "CON10");
  296. assert.equal(searchBoard(data, "rs232_via_transceiver")[0].reference, "CON78");
  297. assert.equal(searchBoard(data, "m10")[0].pinNumber, "1");
  298. assert.ok(searchBoard(data, "对端设备的接收端").some((result) => result.reference === "CON78"));
  299. assert.equal(searchBoard(data, "不能直接接 3.3v ttl")[0].reference, "CON78");
  300. assert.deepEqual(searchBoard(data, "does-not-exist"), []);
  301. });
  302. test("back view mirrors X about the vertical/Y axis for KiCad --mirror SVGs", () => {
  303. assert.equal(BACK_MIRROR_AXIS, "y");
  304. assert.equal(mirrorBoardX(233.275, 430), 196.725);
  305. assert.deepEqual(displayPoint({x: 10, y: 5}, 100, "front"), {x: 10, y: 5});
  306. assert.deepEqual(displayPoint({x: 10, y: 5}, 100, "back"), {x: 90, y: 5});
  307. assert.deepEqual(
  308. displayBounds({x: 10, y: 5, width: 4, height: 2}, 100, "back"),
  309. {x: 86, y: 5, width: 4, height: 2},
  310. );
  311. assert.equal(itemVisibleOnSide({side: "back"}, "back"), true);
  312. assert.equal(itemVisibleOnSide({side: "back"}, "front"), false);
  313. assert.equal(itemVisibleOnSide({side: "front"}, "front"), true);
  314. });
  315. test("pass D/E: exact resistor queries never false-positive on FPGA balls or R1225", () => {
  316. const data = boardData();
  317. data.touchpoints[0].pins[0].fpga.ball = "R7";
  318. data.touchpoints[0].pins[0].path = ["CON78.1", "R63 22R", "FPGA R7"];
  319. const r7 = searchBoard(data, "R7");
  320. assert.equal(r7[0].type, "resistor");
  321. assert.equal(r7[0].reference, "R7");
  322. assert.ok(!r7.some((item) => item.type === "pin" && item.matchedField === "fpga_ball"));
  323. const r12 = searchBoard(data, "R12");
  324. assert.equal(r12[0].type, "resistor");
  325. assert.equal(r12[0].reference, "R12");
  326. assert.ok(!r12.some((item) => item.reference === "R1225"));
  327. assert.equal(searchBoard(data, "R674")[0].type, "resistor");
  328. assert.equal(searchBoard(data, "r674.2")[0].type, "resistor_pad");
  329. assert.equal(searchBoard(data, "r674.2")[0].pinNumber, "2");
  330. assert.equal(identityMatch("R1225", "R12"), 0);
  331. assert.equal(identityMatch("R12", "R12"), 3);
  332. });
  333. test("pass C/F: value and net search cover resistors; sameNetMembers includes resistor pads", () => {
  334. const data = boardData();
  335. assert.equal(parseBoardQuery("4k7").kind, "value");
  336. assert.equal(parseBoardQuery("R674").kind, "resistor_ref");
  337. assert.equal(parseBoardQuery("ball:R7").kind, "ball");
  338. assert.ok(searchBoard(data, "4k7").some((item) => item.reference === "R7"));
  339. assert.ok(searchBoard(data, "22R").some((item) => item.reference === "R12"));
  340. assert.ok(searchBoard(data, "PUL1").some((item) => item.reference === "R7" || item.reference === "R674"));
  341. assert.ok(searchBoard(data, "net:PUL1").some((item) => item.reference === "R674"));
  342. const members = sameNetMembers(data, "PUL1");
  343. assert.ok(members.some((item) => item.kind === "resistor_pad" && item.reference === "R7"));
  344. assert.ok(members.some((item) => item.kind === "resistor_pad" && item.reference === "R674"));
  345. // Compatibility: sameNetPins stays touchpoint-only.
  346. assert.ok(sameNetPins(data, "PUL1").every((item) => item.kind === "touchpoint"));
  347. assert.ok(buildBoardIndex(data).resistorByReference.has("R674"));
  348. });
  349. test("pass D: ball:R7 and U3.R7 disambiguate FPGA balls from resistor R7", () => {
  350. const data = boardData();
  351. data.touchpoints[0].pins[0].fpga.ball = "R7";
  352. data.touchpoints[0].pins[0].path = ["CON78.1", "BANK0", "U3.R7"];
  353. assert.equal(searchBoard(data, "R7")[0].type, "resistor");
  354. const ball = searchBoard(data, "ball:R7");
  355. assert.ok(ball.some((item) => item.type === "pin" && item.pin?.fpga?.ball === "R7"));
  356. assert.ok(searchBoard(data, "U3.R7").some((item) => item.reference === "CON78"));
  357. });
  358. test("pass G path jump extracts annotation resistors and fails closed on missing index", () => {
  359. const data = boardData();
  360. const found = extractPathResistors(data, ["CON78.1", "R7 4.7k", "U3.R4", "FPGA M10"], ["R12 series"]);
  361. assert.deepEqual(found.map((item) => item.reference), ["R7", "R12"]);
  362. assert.throws(
  363. () => extractPathResistors(data, ["R99999 missing"]),
  364. /R99999 missing from resistor index/,
  365. );
  366. });
  367. test("search covers verified MCU device, package pin, signal, and capability", () => {
  368. const data = boardData();
  369. const mcuPin = data.touchpoints.find((item) => item.reference === "TP3").pins[0];
  370. mcuPin.summary = "GD32 firmware test point";
  371. mcuPin.path = [];
  372. mcuPin.programming = {
  373. status: "verified_mcu",
  374. conclusion: "Verified MCU test point",
  375. network_explanation: "Verified MCU path",
  376. hdl_guidance: "Use from firmware",
  377. connection_guidance: [],
  378. constraints: [],
  379. risks: [],
  380. evidence_tier: "cross_verified",
  381. sources: ["fixture"],
  382. };
  383. mcuPin.mcu = {
  384. device: "U27",
  385. family: "GD32F303CGT6",
  386. pin: "10",
  387. signal: "PA0",
  388. capabilities: ["gpio", "adc_input"],
  389. evidence_tier: "cross_verified",
  390. sources: ["fixture"],
  391. };
  392. assert.equal(searchBoard(data, "u27.10")[0].reference, "TP3");
  393. assert.equal(searchBoard(data, "gd32f303")[0].reference, "TP3");
  394. assert.equal(searchBoard(data, "pa0")[0].reference, "TP3");
  395. assert.equal(searchBoard(data, "adc_input")[0].reference, "TP3");
  396. assert.ok(!findCandidates(data, "gpio").some((item) => item.reference === "TP3"));
  397. });
  398. test("same-net lookup returns every matching pad and ignores empty nets", () => {
  399. const data = boardData();
  400. data.touchpoints[1].pins.push(pin({number: "2", net: "RS232_TX2"}));
  401. assert.deepEqual(
  402. sameNetPins(data, "RS232_TX2").map((item) => `${item.reference}.${item.pinNumber}`),
  403. ["CON10.2", "CON78.1"],
  404. );
  405. assert.deepEqual(sameNetPins(data, ""), []);
  406. });
  407. test("candidate filtering is fail-closed and sorted by natural reference and pin", () => {
  408. const candidates = findCandidates(boardData(), "uart_tx");
  409. assert.deepEqual(candidates.map((item) => `${item.reference}.${item.pin.number}`), ["CON10.1"]);
  410. assert.match(candidates[0].reason, /已验证 FPGA 路径/);
  411. assert.match(candidates[0].warning, /当前工程约束冲突/);
  412. });
  413. test("candidate filters recognize canonical board capability aliases", () => {
  414. const aliases = [
  415. ["pwm", "pwm_output"],
  416. ["gpio_output", "digital_output"],
  417. ["gpio_input", "digital_input"],
  418. ["tach", "tach_input"],
  419. ["fan_tach", "tach_input"],
  420. ["presence", "presence_input"],
  421. ];
  422. for (const [filter, capability] of aliases) {
  423. const data = {
  424. touchpoints: [{
  425. reference: "CON1",
  426. category: "CON",
  427. summary: "Alias fixture",
  428. pins: [pin({
  429. fpga: {
  430. ball: "A1",
  431. board_signal: "ALIAS_SIGNAL",
  432. io_standard: "LVCMOS33",
  433. capabilities: ["gpio", capability],
  434. evidence_tier: "cross_verified",
  435. sources: ["fixture"],
  436. },
  437. })],
  438. }],
  439. };
  440. assert.equal(findCandidates(data, filter).length, 1, `${filter} -> ${capability}`);
  441. }
  442. });
  443. test("generic GPIO candidates exclude dedicated tach, PWM, presence, and protocol pins", () => {
  444. const data = {
  445. touchpoints: [{
  446. reference: "CON1",
  447. category: "CON",
  448. summary: "Mixed GPIO fixture",
  449. pins: [
  450. pin({number: "1", function_category: "gpio", summary: "Direct bidirectional GPIO"}),
  451. pin({number: "2", function_category: "fan_tach", summary: "Fan tach input"}),
  452. pin({number: "3", function_category: "pwm", summary: "Open-collector PWM"}),
  453. pin({number: "4", function_category: "presence", summary: "Presence input"}),
  454. ],
  455. }],
  456. };
  457. assert.deepEqual(
  458. findCandidates(data, "gpio").map((item) => `${item.reference}.${item.pin.number}`),
  459. ["CON1.1"],
  460. );
  461. });
  462. test("candidate reason exposes the pin purpose and non-default polarity", () => {
  463. const data = {
  464. touchpoints: [{
  465. reference: "CON31",
  466. category: "CON",
  467. summary: "Fan connector",
  468. pins: [pin({
  469. function_category: "pwm",
  470. summary: "风扇 PWM 开集电极下拉输出",
  471. active_level: "connector low",
  472. polarity: "FPGA high -> connector low",
  473. fpga: {
  474. ball: "E10",
  475. board_signal: "FAN_GPIO6",
  476. io_standard: "LVCMOS33",
  477. capabilities: ["gpio", "pwm_output", "fan_pwm"],
  478. evidence_tier: "cross_verified",
  479. sources: ["fixture"],
  480. },
  481. })],
  482. }],
  483. };
  484. const [candidate] = findCandidates(data, "pwm");
  485. assert.match(candidate.reason, /风扇 PWM 开集电极下拉输出/);
  486. assert.match(candidate.reason, /FPGA high -> connector low/);
  487. });
  488. test("product candidate filters keep dedicated functions out of generic GPIO", () => {
  489. const boardDataPath = resolveGeneratedAsset("board-data.json");
  490. const buildInfoPath = resolveGeneratedAsset("build-info.json");
  491. const expectationPath = new URL("./fixtures/candidate_count_expectation.json", import.meta.url);
  492. const boardDataBytes = readFileSync(boardDataPath);
  493. const buildInfoBytes = readFileSync(buildInfoPath);
  494. const data = JSON.parse(boardDataBytes);
  495. const expectation = JSON.parse(readFileSync(expectationPath, "utf8"));
  496. const boardDataSha = createHash("sha256").update(boardDataBytes).digest("hex");
  497. const buildInfoSha = createHash("sha256").update(buildInfoBytes).digest("hex");
  498. assert.equal(expectation.schema, "prod2u-board-viewer-candidate-count-expectation-v1");
  499. assert.equal(boardDataSha, expectation.bound_to.board_data_sha256);
  500. assert.equal(buildInfoSha, expectation.bound_to.build_info_sha256);
  501. assert.equal(boardDataSha, expectation.bound_to.board_data_asset_sha256);
  502. for (const [capability, expectedCount] of Object.entries(expectation.candidate_counts)) {
  503. const candidates = findCandidates(data, capability);
  504. assert.equal(candidates.length, expectedCount, `${capability} count`);
  505. if (Array.isArray(expectation.candidate_keys?.[capability])) {
  506. assert.deepEqual(
  507. candidates.map((item) => `${item.reference}.${item.pin.number}`),
  508. expectation.candidate_keys[capability],
  509. `${capability} keys`,
  510. );
  511. }
  512. }
  513. assert.ok(findCandidates(data, "gpio").every((item) => item.pin.function_category === "gpio"));
  514. });
  515. test("unknown, inferred, power, ground, mechanical, reserved, and fixed-load pins are never candidates", () => {
  516. const blockers = [
  517. {evidence_tier: "unknown"},
  518. {evidence_tier: "name_inferred"},
  519. {function_category: "power", net: "+3V3"},
  520. {function_category: "ground", net: "GND"},
  521. {mechanical: true, electrical: false},
  522. {pad_role: "shield"},
  523. {pad_role: "unknown"},
  524. {reserved: true},
  525. {fixed_load_conflict: true},
  526. ];
  527. for (const [index, override] of blockers.entries()) {
  528. const data = {touchpoints: [{reference: `J${index + 1}`, category: "J", summary: "", pins: [pin(override)]}]};
  529. assert.deepEqual(findCandidates(data, "uart_tx"), []);
  530. }
  531. });
  532. test("connector groups follow reviewed board-front order and separate auxiliary pads", () => {
  533. const touchpoint = {
  534. reference: "CON78",
  535. connector: {
  536. review_status: "cross_verified",
  537. contact_order: ["1", "2", "3", "4"],
  538. contact_grid: [["1"], ["2"], ["3"], ["4"]],
  539. },
  540. pins: [
  541. pin({id: "shield-5", number: "5", pad_role: "shield"}),
  542. pin({id: "contact-4", number: "4"}),
  543. pin({id: "contact-2", number: "2"}),
  544. pin({id: "mechanical-1", number: "", pad_role: "mechanical", mechanical: true, electrical: false}),
  545. pin({id: "contact-1", number: "1"}),
  546. pin({id: "contact-3", number: "3"}),
  547. ],
  548. };
  549. const groups = connectorPinGroups(touchpoint);
  550. assert.deepEqual(groups.contactRows.map((row) => row.map((item) => item.number)), [["1"], ["2"], ["3"], ["4"]]);
  551. assert.deepEqual(groups.contacts.map((item) => item.number), ["1", "2", "3", "4"]);
  552. assert.deepEqual(groups.auxiliary.map((item) => item.id), ["shield-5", "mechanical-1"]);
  553. });
  554. test("unknown connector layout never invents contact ordering", () => {
  555. const touchpoint = {
  556. reference: "CON1",
  557. connector: {review_status: "unknown", contact_order: [], contact_grid: []},
  558. pins: [pin({id: "unknown-1", pad_role: "unknown"})],
  559. };
  560. assert.deepEqual(connectorPinGroups(touchpoint), {
  561. contactRows: [],
  562. contacts: [],
  563. auxiliary: [touchpoint.pins[0]],
  564. });
  565. });
  566. test("RTL port names reject syntax that could escape an ADC assignment", () => {
  567. for (const name of ["uart_tx", "fan_pwm_out[3]", "_debug$signal"]) {
  568. assert.equal(isValidRtlPortName(name), true, name);
  569. }
  570. for (const name of ["", "3bad", "a b", "a;set", "name[foo]", "{signal}", "a\nnext"]) {
  571. assert.equal(isValidRtlPortName(name), false, name);
  572. }
  573. });
  574. test("ADC generation requires current verified eligible data and omits implicit PULLTYPE", () => {
  575. const data = boardData();
  576. const pwm = data.touchpoints[2].pins[0];
  577. const snippet = generateAdcSnippet(pwm, "fan_pwm_out[3]", {adcCopyEnabled: true});
  578. assert.equal(
  579. snippet,
  580. "set_pin_assignment { fan_pwm_out[3] } { LOCATION = B2; IOSTANDARD = LVCMOS33; }",
  581. );
  582. assert.doesNotMatch(snippet, /PULLTYPE/);
  583. assert.throws(() => generateAdcSnippet(pwm, "a;bad", {adcCopyEnabled: true}), /合法的 RTL 端口名/);
  584. assert.throws(() => generateAdcSnippet(pwm, "fan_pwm_out", {adcCopyEnabled: false}), /源数据已过期/);
  585. assert.throws(
  586. () => generateAdcSnippet(data.touchpoints[0].pins[0], "uart2_tx", {adcCopyEnabled: true}),
  587. /不具备 ADC 生成资格/,
  588. );
  589. });
  590. test("ADC generation includes PULLTYPE only when curated annotation explicitly supplies it", () => {
  591. const pinWithPulltype = boardData().touchpoints[2].pins[1];
  592. assert.equal(
  593. generateAdcSnippet(pinWithPulltype, "fan_pwm_aux", {adcCopyEnabled: true}),
  594. "set_pin_assignment { fan_pwm_aux } { LOCATION = B3; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }",
  595. );
  596. });
  597. test("pass C/D: 0805 is not a resistance query; 0R/120R grammar; bare PUL1 exact net", () => {
  598. const data = boardData();
  599. // Inject path text noise that must NOT match bare exact-net PUL1.
  600. data.touchpoints[0].pins[0].path = ["mentions PUL1 in prose only", "FPGA M10"];
  601. data.touchpoints[0].pins[0].net = "RS232_TX2";
  602. assert.notEqual(parseBoardQuery("0805").kind, "value");
  603. assert.equal(parseBoardQuery("0R").kind, "value");
  604. assert.equal(parseBoardQuery("120R").kind, "value");
  605. assert.equal(resolveExactNetName(data, "PUL1"), "PUL1");
  606. const bare = searchBoard(data, "PUL1");
  607. const prefixed = searchBoard(data, "net:PUL1");
  608. assert.deepEqual(
  609. bare.map((item) => `${item.type}:${item.reference}.${item.pinNumber}`).sort(),
  610. prefixed.map((item) => `${item.type}:${item.reference}.${item.pinNumber}`).sort(),
  611. );
  612. assert.ok(bare.every((item) => item.matchedField === "net"));
  613. assert.ok(!bare.some((item) => item.reference === "CON78"));
  614. // Fixture 4k7 grammar still works on synthetic R7.
  615. assert.ok(searchBoard(data, "4k7").some((item) => item.reference === "R7"));
  616. });
  617. test("peripheral index resolves FPGA/MCU logical pins across V1.2, V2.0, and V2.0 Fan boards", () => {
  618. const v12Data = JSON.parse(readFileSync(resolveGeneratedAsset("board-data.json"), "utf8"));
  619. const v12Idx = buildPeripheralIndex(v12Data, "v1_2");
  620. const con140 = v12Idx.items.find((item) => item.reference === "CON140");
  621. assert.ok(con140);
  622. assert.equal(con140.peripheralType, "UART");
  623. assert.equal(con140.isUsed, true);
  624. const tx = con140.pins.find((p) => p.pinNumber === "1").logical;
  625. const rx = con140.pins.find((p) => p.pinNumber === "2").logical;
  626. assert.equal(tx.physicalPin, "U3.T11");
  627. assert.match(tx.logicalSignal, /host_ttl_tx/);
  628. assert.equal(rx.physicalPin, "U3.P13");
  629. assert.match(rx.logicalSignal, /host_ttl_rx/);
  630. for (const p of con140.pins.filter((p) => ["3", "4"].includes(p.pinNumber))) {
  631. assert.doesNotMatch(p.logical.logicalSignal, /GND/);
  632. }
  633. const con146 = v12Idx.items.find((item) => item.reference === "CON146");
  634. assert.equal(con146.isUsed, true);
  635. assert.match(con146.pins.find((p) => p.pinNumber === "1").logical.pinDefinition, /12V/);
  636. assert.match(con146.pins.find((p) => p.pinNumber === "1").logical.logicalSignal, /buzzer_out/);
  637. const v20Url = new URL("../../tools/board-viewer/generated-v2_0/board-data.json", import.meta.url);
  638. if (existsSync(fileURLToPath(v20Url))) {
  639. const v20Data = JSON.parse(readFileSync(v20Url, "utf8"));
  640. const v20Idx = buildPeripheralIndex(v20Data, "v2_0");
  641. assert.equal(v20Idx.items.length, 74);
  642. // PTC1 lookup returns CON147 with U3.F16
  643. const ptc1Matches = filterPeripheralCatalog(v20Data, "v2_0", {category: "PTC", query: "PTC1"}).filteredItems;
  644. assert.ok(ptc1Matches.some((item) => item.reference === "CON147"));
  645. const con147 = v20Idx.items.find((item) => item.reference === "CON147");
  646. const con147Pin1 = con147.pins.find((p) => p.pinNumber === "1");
  647. assert.equal(con147Pin1.logical.physicalPin, "U3.F16");
  648. assert.match(con147Pin1.logical.logicalSignal, /ptc_pwm_out\[0\]/);
  649. // CON149.19 = channel18, then CON150 PTC31..35 = channels19..23
  650. const con150 = v20Idx.items.find((item) => item.reference === "CON150");
  651. assert.equal(con150.pins.find((p) => p.pinNumber === "13").logical.physicalPin, "U3.H5");
  652. assert.match(con150.pins.find((p) => p.pinNumber === "13").logical.logicalSignal, /ptc_pwm_out\[22\]/);
  653. assert.equal(con150.pins.find((p) => p.pinNumber === "17").logical.physicalPin, "U3.C15");
  654. assert.match(con150.pins.find((p) => p.pinNumber === "17").logical.logicalSignal, /ptc_pwm_out\[23\]/);
  655. const con149 = v20Idx.items.find((item) => item.reference === "CON149");
  656. assert.equal(con149.pins.find((p) => p.pinNumber === "13").logical.physicalPin, "U3.P2");
  657. assert.equal(con149.pins.find((p) => p.pinNumber === "13").logical.isUsed, false);
  658. assert.equal(con149.pins.find((p) => p.pinNumber === "19").logical.physicalPin, "U3.K5");
  659. assert.match(con149.pins.find((p) => p.pinNumber === "19").logical.logicalSignal, /ptc_pwm_out\[18\]/);
  660. // CON103 resolves to onboard STM32 U27.12/13 (with schematic -CON103 vs CON12 note)
  661. const con103 = v20Idx.items.find((item) => item.reference === "CON103");
  662. assert.match(con103.pins.find((p) => p.pinNumber === "1").logical.physicalPin, /U27\.12/);
  663. assert.match(con103.pins.find((p) => p.pinNumber === "2").logical.physicalPin, /U27\.13/);
  664. // CON159 resolves Page 3/4 1#腔体步进控制 X1/Y1/Z1/A1 (-M1..-M4) while remaining spare in 6400 32B protocol
  665. const con159 = v20Idx.items.find((item) => item.reference === "CON159");
  666. assert.equal(con159.pins.find((p) => p.pinNumber === "1").logical.physicalPin, "U3.C12");
  667. assert.match(con159.pins.find((p) => p.pinNumber === "1").logical.peripheralRole, /1#前部风门/);
  668. assert.equal(con159.pins.find((p) => p.pinNumber === "7").logical.physicalPin, "U3.L13");
  669. assert.match(con159.pins.find((p) => p.pinNumber === "7").logical.peripheralRole, /2#前部风门/);
  670. // JTAG lookup returns J3 (10-pin FPGA JTAG) and J25 (5-pin MCU SWD)
  671. const jtagMatches = filterPeripheralCatalog(v20Data, "v2_0", {category: "JTAG"}).filteredItems;
  672. const jtagRefs = jtagMatches.map((item) => item.reference);
  673. assert.ok(jtagRefs.includes("J3"));
  674. assert.ok(jtagRefs.includes("J25"));
  675. // Spare connector filter includes CON156..163, CON170, CON171, CON172
  676. const spareMatches = filterPeripheralCatalog(v20Data, "v2_0", {usage: "spare"}).filteredItems;
  677. const spareRefs = new Set(spareMatches.map((item) => item.reference));
  678. for (const ref of ["CON156", "CON159", "CON170", "CON171", "CON172"]) {
  679. assert.ok(spareRefs.has(ref), `${ref} should be in spare connectors`);
  680. }
  681. }
  682. });
  683. test("CPLD architecture multi-level menu and RTL module knowledge base cover all board versions and 29 topics", async () => {
  684. const {
  685. CPLD_CHIP_SPEC,
  686. BOARD_VERSION_COMM_MATRIX,
  687. CPLD_MENU_TREE,
  688. getCpldTopicDetail,
  689. } = await import("../../tools/board-viewer/web/cpld-arch-data.mjs");
  690. assert.equal(CPLD_CHIP_SPEC.partNumber, "EF2L45BG256B");
  691. assert.equal(CPLD_CHIP_SPEC.clockFreqHz, 25_000_000);
  692. // Check all 4 board versions in communication matrix
  693. for (const ver of ["v2_0", "v2_0_fan", "v1_2", "v1_1"]) {
  694. assert.ok(BOARD_VERSION_COMM_MATRIX[ver], `missing board version ${ver}`);
  695. assert.ok(BOARD_VERSION_COMM_MATRIX[ver].topModule);
  696. assert.ok(BOARD_VERSION_COMM_MATRIX[ver].hostTtl?.connector);
  697. }
  698. assert.match(BOARD_VERSION_COMM_MATRIX.v1_2.hostTtl.connector, /CON140/);
  699. assert.match(BOARD_VERSION_COMM_MATRIX.v2_0.hostTtl.connector, /CON12/);
  700. assert.match(BOARD_VERSION_COMM_MATRIX.v1_1.hostTtl.connector, /CON30/);
  701. // Check 3-level hierarchy (L1 domains -> L2 subsystem children -> L3 topics)
  702. assert.equal(CPLD_MENU_TREE.length, 4);
  703. const allTopics = [];
  704. for (const domain of CPLD_MENU_TREE) {
  705. assert.ok(domain.id && domain.title && Array.isArray(domain.children) && domain.children.length > 0);
  706. for (const group of domain.children) {
  707. assert.ok(group.id && group.title && Array.isArray(group.topics) && group.topics.length > 0);
  708. for (const topic of group.topics) {
  709. assert.ok(topic.id && topic.title);
  710. allTopics.push(topic.id);
  711. }
  712. }
  713. }
  714. assert.equal(allTopics.length, 29);
  715. // Check every L3 topic detail across versions
  716. for (const topicId of allTopics) {
  717. for (const ver of ["v2_0", "v1_2", "v1_1"]) {
  718. const detail = getCpldTopicDetail(topicId, ver);
  719. assert.ok(detail.title, `missing title for ${topicId}`);
  720. assert.ok(detail.file, `missing file for ${topicId}`);
  721. assert.ok(detail.summary, `missing summary for ${topicId}`);
  722. const hasContent =
  723. Boolean(detail.kvTable?.length)
  724. || Boolean(detail.matrixTable?.rows?.length)
  725. || Boolean(detail.pipelineFlow?.length)
  726. || Boolean(detail.codeBlock);
  727. assert.ok(hasContent, `missing content sections for ${topicId}`);
  728. }
  729. }
  730. });
  731. test("Rust WebAssembly spatial index supports culling and selected pin hit tests", async () => {
  732. const {BoardWasmAccelerator} = await import("../../tools/board-viewer/web/wasm-engine.mjs");
  733. const wasmUrl = new URL("../../tools/board-viewer/web/board-accel.wasm", import.meta.url);
  734. const wasmBytes = readFileSync(fileURLToPath(wasmUrl));
  735. assert.equal(wasmBytes[0], 0x00);
  736. assert.equal(wasmBytes[1], 0x61); // 'a'
  737. assert.equal(wasmBytes[2], 0x73); // 's'
  738. assert.equal(wasmBytes[3], 0x6d); // 'm'
  739. const accel = new BoardWasmAccelerator();
  740. const ok = await accel.init(wasmBytes);
  741. assert.equal(ok, true);
  742. assert.equal(accel.engineType, "Rust-WASM");
  743. const v12Data = JSON.parse(readFileSync(resolveGeneratedAsset("board-data.json"), "utf8"));
  744. accel.buildIndex(v12Data);
  745. assert.ok(accel.totalIndexedCount > 2000, `expected >2000 indexed items, got ${accel.totalIndexedCount}`);
  746. // 1. Viewport frustum culling on full board vs zoomed-in sub-region
  747. const cats = new Set(["CON", "J", "PL", "TP", "R"]);
  748. const fullCull = accel.cullViewport(
  749. {x: 0, y: 0, width: 430, height: 75},
  750. "front",
  751. cats,
  752. false,
  753. 1.0,
  754. null,
  755. );
  756. assert.ok(fullCull && fullCull.count > 100);
  757. assert.ok(accel.lastCullMs < 15, `expected cull < 15ms, got ${accel.lastCullMs}ms`);
  758. const subCull = accel.cullViewport(
  759. {x: 10, y: 10, width: 25, height: 15},
  760. "front",
  761. cats,
  762. false,
  763. 8.0,
  764. null,
  765. );
  766. assert.ok(subCull && subCull.count < fullCull.count);
  767. // 2. Spatial grid hit-test on CON146 Pin 1
  768. const con146 = v12Data.touchpoints.find((tp) => tp.reference === "CON146");
  769. assert.ok(con146);
  770. const pin1 = con146.pins.find((p) => String(p.number) === "1");
  771. assert.ok(pin1);
  772. const hit = accel.hitTest(
  773. pin1.view_position.x,
  774. pin1.view_position.y,
  775. "front",
  776. cats,
  777. false,
  778. 4.0,
  779. );
  780. assert.ok(hit);
  781. assert.equal(hit.kind, "pin");
  782. assert.equal(hit.touchpoint.reference, "CON146");
  783. assert.equal(String(hit.pin.number), "1");
  784. });