| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790 |
- const VERIFIED = "cross_verified";
- const POWER_NET = /^(?:GND|AGND|DGND|PGND|EARTH|VCC|VDD|VBAT|PWR|\+)/i;
- const RTL_PORT = /^[A-Za-z_][A-Za-z0-9_$]*(?:\[[0-9]+\])?$/;
- const RESISTOR_REF = /^r(\d+)$/i;
- const RESISTOR_PAD = /^r(\d+)\.(\d+)$/i;
- const BALL_PREFIX = /^ball:(.+)$/i;
- const NET_PREFIX = /^net:(.+)$/i;
- const VALUE_PREFIX = /^value:(.+)$/i;
- const ENDPOINT = /^u\d+\.[a-z]+\d+$/i;
- const ANNOTATION_RESISTOR = /(?<![A-Za-z0-9.])R(\d+)\b/g;
- const VALUE_GRAMMAR = /^(?:\d+(?:\.\d+)?[rRkKmM]\d*|\d+[rRkKmM]|\d+(?:\.\d+)?(?:ohm|ohms|Ω)?)$/i;
- const PACKAGE_OR_DNP = /^(?:0603|0805|0402|1206|1210|2010|2512|dnp|nc|n\/?c)$/i;
- const CAPABILITY_ALIASES = {
- pwm: ["pwm", "pwm_output"],
- gpio_output: ["gpio_output", "digital_output"],
- gpio_input: ["gpio_input", "digital_input"],
- tach: ["tach", "tach_input"],
- fan_tach: ["fan_tach", "tach_input"],
- presence: ["presence", "presence_input"],
- };
- function text(value) {
- return value == null ? "" : String(value);
- }
- function normalized(value) {
- return text(value).trim().toLocaleLowerCase();
- }
- function naturalCompare(left, right) {
- return text(left).localeCompare(text(right), undefined, {numeric: true, sensitivity: "base"});
- }
- function capabilities(pin) {
- return Array.isArray(pin?.fpga?.capabilities) ? pin.fpga.capabilities.map(text) : [];
- }
- function baseBlockers(pin) {
- const blockers = [];
- if (pin?.evidence_tier !== VERIFIED || pin?.fpga?.evidence_tier !== VERIFIED) {
- blockers.push("unverified");
- }
- if (!pin?.fpga?.ball || !pin?.fpga?.io_standard) blockers.push("missing_fpga_assignment");
- if (pin?.mechanical === true || pin?.electrical !== true) blockers.push("mechanical_or_non_electrical");
- if (pin?.pad_role !== "contact") blockers.push("not_connector_contact");
- if (["power", "ground"].includes(pin?.function_category) || POWER_NET.test(text(pin?.net))) {
- blockers.push("power_or_ground");
- }
- if (pin?.reserved === true) blockers.push("reserved");
- if (pin?.fixed_load_conflict === true) blockers.push("fixed_load_conflict");
- if (["", "unknown"].includes(normalized(pin?.external_level))) blockers.push("external_level_unknown");
- return blockers;
- }
- export function connectorPinGroups(touchpoint) {
- const pins = Array.isArray(touchpoint?.pins) ? touchpoint.pins : [];
- const connector = touchpoint?.connector;
- const reviewed = connector?.review_status === VERIFIED;
- const grid = reviewed && Array.isArray(connector?.contact_grid) ? connector.contact_grid : [];
- const byNumber = new Map(
- pins
- .filter((pin) => pin?.pad_role === "contact" && text(pin?.number))
- .map((pin) => [text(pin.number), pin]),
- );
- const contactRows = grid.map((row) =>
- (Array.isArray(row) ? row : []).map((number) => byNumber.get(text(number))).filter(Boolean),
- );
- return {
- contactRows,
- contacts: contactRows.flat(),
- auxiliary: pins.filter((pin) => pin?.pad_role !== "contact"),
- };
- }
- function pinSearchFields(touchpoint, pin) {
- const programming = pin?.programming ?? {};
- return [
- ["pin", `${touchpoint.reference}.${pin.number}`],
- ["reference", touchpoint.reference],
- ["pin_number", pin.number],
- ["net", pin.net],
- ["summary", pin.summary],
- ["function", pin.function_category],
- ["direction", pin.direction],
- ["external_level", pin.external_level],
- ["fpga_ball", pin.fpga?.ball],
- ["board_signal", pin.fpga?.board_signal],
- ["capability", capabilities(pin).join(" ")],
- ["mcu_device", pin.mcu?.device],
- ["mcu_family", pin.mcu?.family],
- ["mcu_pin", pin.mcu?.device && pin.mcu?.pin ? `${pin.mcu.device}.${pin.mcu.pin}` : ""],
- ["mcu_signal", pin.mcu?.signal],
- ["mcu_capability", Array.isArray(pin.mcu?.capabilities) ? pin.mcu.capabilities.join(" ") : ""],
- ["path", Array.isArray(pin.path) ? pin.path.join(" ") : ""],
- ["programming_conclusion", programming.conclusion],
- ["network_explanation", programming.network_explanation],
- ["hdl_guidance", programming.hdl_guidance],
- ["connection_guidance", Array.isArray(programming.connection_guidance) ? programming.connection_guidance.join(" ") : ""],
- ["programming_constraints", Array.isArray(programming.constraints) ? programming.constraints.join(" ") : ""],
- ["programming_risks", Array.isArray(programming.risks) ? programming.risks.join(" ") : ""],
- ];
- }
- /**
- * Safe reference / identity match: exact, or prefix only when the next char is not a digit.
- * Prevents R12 ⊆ R1225 false positives.
- */
- export function identityMatch(candidate, query) {
- const value = normalized(candidate);
- const needle = normalized(query);
- if (!value || !needle) return 0;
- if (value === needle) return 3;
- if (value.startsWith(needle)) {
- const next = value.charAt(needle.length);
- if (!next || !/\d/.test(next)) return 2;
- return 0;
- }
- return 0;
- }
- function fieldScore(field, value, query, {allowIncludes = true} = {}) {
- const candidate = normalized(value);
- if (!candidate) return 0;
- const weights = {
- pin: 1200,
- reference: 1000,
- resistor: 1600,
- resistor_pad: 1500,
- value: 1400,
- fpga_ball: 900,
- mcu_pin: 900,
- mcu_signal: 840,
- mcu_device: 800,
- mcu_family: 780,
- mcu_capability: 720,
- net: 850,
- board_signal: 820,
- function: 760,
- capability: 720,
- pin_number: 620,
- summary: 500,
- path: 460,
- programming_conclusion: 700,
- network_explanation: 610,
- hdl_guidance: 590,
- connection_guidance: 570,
- programming_constraints: 540,
- programming_risks: 480,
- external_level: 420,
- direction: 360,
- };
- const weight = weights[field] ?? 200;
- if (field === "reference" || field === "resistor" || field === "resistor_pad" || field === "pin") {
- const grade = identityMatch(candidate, query);
- if (grade === 3) return weight;
- if (grade === 2) return weight - 120;
- return 0;
- }
- if (field === "fpga_ball") {
- // Identifiers: exact / token boundary only — never bare includes.
- if (candidate === query) return weight;
- return 0;
- }
- if (candidate === query) return weight;
- if (candidate.startsWith(query)) return weight - 120;
- if (allowIncludes && candidate.includes(query)) return weight - 240;
- return 0;
- }
- function resultId(type, reference, pinNumber = null) {
- return pinNumber == null ? `${type}:${reference}` : `${type}:${reference}.${pinNumber}`;
- }
- export function buildBoardIndex(data) {
- const resistorByReference = new Map();
- const resistorPadById = new Map();
- const valueTokenIndex = new Map();
- const netMembers = new Map();
- const relatedByPinId = new Map();
- const pushNet = (net, member) => {
- const key = text(net);
- if (!key) return;
- if (!netMembers.has(key)) netMembers.set(key, []);
- netMembers.get(key).push(member);
- };
- for (const resistor of data?.resistors ?? []) {
- const reference = text(resistor.reference);
- resistorByReference.set(reference, resistor);
- resistorByReference.set(normalized(reference), resistor);
- for (const token of resistor.value_tokens ?? []) {
- const key = normalized(token);
- if (!key) continue;
- if (!valueTokenIndex.has(key)) valueTokenIndex.set(key, []);
- valueTokenIndex.get(key).push(resistor);
- }
- for (const pad of resistor.pads ?? []) {
- const padId = text(pad.id) || `${reference}.pad-${pad.number}`;
- resistorPadById.set(padId, {resistor, pad});
- resistorPadById.set(`${reference}.${pad.number}`, {resistor, pad});
- pushNet(pad.net, {
- kind: "resistor_pad",
- reference,
- pinNumber: text(pad.number),
- touchpoint: null,
- resistor,
- pin: pad,
- });
- }
- }
- for (const touchpoint of data?.touchpoints ?? []) {
- for (const pin of touchpoint.pins ?? []) {
- pushNet(pin.net, {
- kind: "touchpoint",
- reference: touchpoint.reference,
- pinNumber: text(pin.number),
- touchpoint,
- resistor: null,
- pin,
- });
- if (Array.isArray(pin.related_resistors) && pin.related_resistors.length) {
- relatedByPinId.set(text(pin.id), pin.related_resistors);
- }
- }
- }
- for (const members of netMembers.values()) {
- members.sort((left, right) => {
- const referenceOrder = naturalCompare(left.reference, right.reference);
- return referenceOrder || naturalCompare(left.pinNumber, right.pinNumber);
- });
- }
- return {
- resistorByReference,
- resistorPadById,
- valueTokenIndex,
- netMembers,
- relatedByPinId,
- evidenceConflicts: Array.isArray(data?.evidence_conflicts) ? data.evidence_conflicts : [],
- };
- }
- function looksLikeResistanceToken(raw) {
- const needle = text(raw).trim();
- if (!needle) return false;
- if (PACKAGE_OR_DNP.test(needle)) return false;
- if (!VALUE_GRAMMAR.test(needle)) return false;
- if (/^\d{1,2}$/.test(needle)) return false; // short bare numbers need value: or 22R
- // Bare package-sized integers like 0805 already rejected; reject 4-digit bare
- // numbers that look like imperial package codes when no unit suffix present.
- if (/^\d{4}$/.test(needle) && !/[rRkKmM]|ohm|Ω/i.test(needle)) return false;
- return true;
- }
- /** Resolve exact net name from board index; case-sensitive first, then CI. */
- export function resolveExactNetName(data, query) {
- const raw = text(query).trim();
- if (!raw) return null;
- const index = buildBoardIndex(data);
- if (index.netMembers.has(raw)) return raw;
- const needle = normalized(raw);
- for (const name of index.netMembers.keys()) {
- if (normalized(name) === needle) return name;
- }
- return null;
- }
- export function parseBoardQuery(query) {
- const raw = text(query).trim();
- const needle = normalized(raw);
- if (!needle) return {kind: "empty", raw, needle};
- const ball = BALL_PREFIX.exec(raw);
- if (ball) return {kind: "ball", raw, needle: normalized(ball[1]), value: ball[1].trim()};
- const net = NET_PREFIX.exec(raw);
- if (net) return {kind: "net", raw, needle: normalized(net[1]), value: net[1].trim()};
- const value = VALUE_PREFIX.exec(raw);
- if (value) return {kind: "value", raw, needle: normalized(value[1]), value: value[1].trim()};
- const pad = RESISTOR_PAD.exec(needle);
- if (pad) {
- return {
- kind: "resistor_pad",
- raw,
- needle,
- reference: `R${pad[1]}`,
- padNumber: pad[2],
- };
- }
- const ref = RESISTOR_REF.exec(needle);
- if (ref) {
- return {
- kind: "resistor_ref",
- raw,
- needle,
- reference: `R${ref[1]}`,
- };
- }
- if (ENDPOINT.test(needle)) {
- return {kind: "endpoint", raw, needle, value: raw};
- }
- if (looksLikeResistanceToken(raw)) {
- return {kind: "value", raw, needle, value: raw};
- }
- return {kind: "text", raw, needle};
- }
- function sortResults(results) {
- const typeOrder = {
- resistor: 0,
- resistor_pad: 1,
- evidence_conflict: 2,
- touchpoint: 3,
- pin: 4,
- };
- return results.sort((left, right) => {
- if (right.score !== left.score) return right.score - left.score;
- const leftType = typeOrder[left.type] ?? 9;
- const rightType = typeOrder[right.type] ?? 9;
- if (leftType !== rightType) return leftType - rightType;
- const referenceOrder = naturalCompare(left.reference, right.reference);
- if (referenceOrder) return referenceOrder;
- return naturalCompare(left.pinNumber, right.pinNumber);
- });
- }
- function searchTouchpoints(data, needle, {ballOnly = false, endpoint = null} = {}) {
- const results = [];
- for (const touchpoint of data?.touchpoints ?? []) {
- if (!ballOnly && !endpoint) {
- const touchpointFields = [
- ["reference", touchpoint.reference],
- ["summary", touchpoint.summary],
- ["function", touchpoint.category],
- ];
- let touchpointScore = 0;
- let touchpointField = "";
- for (const [field, value] of touchpointFields) {
- const score = fieldScore(field, value, needle);
- if (score > touchpointScore) {
- touchpointScore = score;
- touchpointField = field;
- }
- }
- if (touchpointScore) {
- results.push({
- id: resultId("touchpoint", touchpoint.reference),
- type: "touchpoint",
- reference: touchpoint.reference,
- pinNumber: null,
- touchpoint,
- resistor: null,
- pin: null,
- matchedField: touchpointField,
- score: touchpointScore + 20,
- });
- }
- }
- for (const pin of touchpoint.pins ?? []) {
- let score = 0;
- let matchedField = "";
- if (ballOnly) {
- const ballScore = fieldScore("fpga_ball", pin.fpga?.ball, needle, {allowIncludes: false});
- if (!ballScore) continue;
- score = ballScore;
- matchedField = "fpga_ball";
- } else if (endpoint) {
- const endpointNeedle = normalized(endpoint);
- const candidates = [
- ["fpga_ball", `u3.${text(pin.fpga?.ball)}`],
- ["path", Array.isArray(pin.path) ? pin.path.join(" ") : ""],
- ["board_signal", pin.fpga?.board_signal],
- ["pin", `${touchpoint.reference}.${pin.number}`],
- ];
- for (const [field, value] of candidates) {
- const candidate = normalized(value);
- if (!candidate) continue;
- if (candidate === endpointNeedle || candidate.includes(endpointNeedle)) {
- const candidateScore = field === "fpga_ball" ? 950 : 700;
- if (candidateScore > score) {
- score = candidateScore;
- matchedField = field;
- }
- }
- }
- if (!score) continue;
- } else {
- for (const [field, value] of pinSearchFields(touchpoint, pin)) {
- const candidateScore = fieldScore(field, value, needle, {
- allowIncludes: field !== "fpga_ball" && field !== "reference" && field !== "pin",
- });
- if (candidateScore > score) {
- score = candidateScore;
- matchedField = field;
- }
- }
- if (!score) continue;
- if (baseBlockers(pin).length === 0) score += 40;
- }
- results.push({
- id: resultId("pin", touchpoint.reference, text(pin.number)),
- type: "pin",
- reference: touchpoint.reference,
- pinNumber: text(pin.number),
- touchpoint,
- resistor: null,
- pin,
- matchedField,
- score,
- });
- }
- }
- return results;
- }
- function pushNetMemberResults(results, members, score = 1400) {
- for (const member of members) {
- const isResistor = member.kind === "resistor_pad";
- results.push({
- id: resultId(isResistor ? "resistor_pad" : "pin", member.reference, member.pinNumber),
- type: isResistor ? "resistor_pad" : "pin",
- reference: member.reference,
- pinNumber: member.pinNumber,
- touchpoint: member.touchpoint,
- resistor: member.resistor,
- pin: member.pin,
- matchedField: "net",
- score,
- assemblyStatus: member.resistor?.assembly_status || null,
- });
- }
- }
- export function searchBoard(data, query) {
- let parsed = parseBoardQuery(query);
- if (parsed.kind === "empty") return [];
- const index = buildBoardIndex(data);
- let results = [];
- // Bare string that exactly equals an existing net → exact net query (same as net:).
- if (parsed.kind === "text") {
- const exactNet = resolveExactNetName(data, parsed.raw);
- if (exactNet) {
- parsed = {kind: "net", raw: parsed.raw, needle: normalized(exactNet), value: exactNet};
- }
- }
- if (parsed.kind === "resistor_pad") {
- const hit = index.resistorPadById.get(`${parsed.reference}.${parsed.padNumber}`);
- if (hit) {
- results.push({
- id: resultId("resistor_pad", parsed.reference, parsed.padNumber),
- type: "resistor_pad",
- reference: parsed.reference,
- pinNumber: parsed.padNumber,
- touchpoint: null,
- resistor: hit.resistor,
- pin: hit.pad,
- matchedField: "resistor_pad",
- score: 1550,
- });
- }
- return sortResults(results);
- }
- if (parsed.kind === "resistor_ref") {
- const resistor = index.resistorByReference.get(parsed.reference)
- || index.resistorByReference.get(normalized(parsed.reference));
- if (resistor) {
- results.push({
- id: resultId("resistor", parsed.reference),
- type: "resistor",
- reference: parsed.reference,
- pinNumber: null,
- touchpoint: null,
- resistor,
- pin: null,
- matchedField: "resistor",
- score: 1600,
- });
- }
- return sortResults(results);
- }
- if (parsed.kind === "ball") {
- return sortResults(searchTouchpoints(data, parsed.needle, {ballOnly: true}));
- }
- if (parsed.kind === "endpoint") {
- return sortResults(searchTouchpoints(data, parsed.needle, {endpoint: parsed.value}));
- }
- if (parsed.kind === "net") {
- const members =
- index.netMembers.get(text(parsed.value))
- || index.netMembers.get(parsed.value)
- || [];
- pushNetMemberResults(results, members, 1400);
- if (!results.length) {
- for (const [net, rows] of index.netMembers.entries()) {
- if (normalized(net) !== parsed.needle) continue;
- pushNetMemberResults(results, rows, 1400);
- }
- }
- return sortResults(results);
- }
- if (parsed.kind === "value") {
- const seen = new Set();
- const addResistor = (resistor, score = 1400) => {
- const reference = text(resistor.reference);
- if (seen.has(reference)) return;
- seen.add(reference);
- const notFitted = resistor.assembly_status === "not_fitted";
- results.push({
- id: resultId("resistor", reference),
- type: "resistor",
- reference,
- pinNumber: null,
- touchpoint: null,
- resistor,
- pin: null,
- matchedField: "value",
- score: notFitted ? score - 200 : score,
- assemblyStatus: resistor.assembly_status || "unknown",
- notFitted,
- });
- };
- for (const resistor of index.valueTokenIndex.get(parsed.needle) ?? []) {
- addResistor(resistor, 1450);
- }
- for (const resistor of data?.resistors ?? []) {
- for (const token of resistor.value_tokens ?? []) {
- if (normalized(token) === parsed.needle) addResistor(resistor, 1450);
- }
- if (normalized(resistor.component_value) === parsed.needle) addResistor(resistor, 1400);
- }
- return sortResults(results);
- }
- // Free-text (non-exact-net): touchpoints/pins; value tokens; never bare R# here.
- results = searchTouchpoints(data, parsed.needle);
- for (const resistor of index.valueTokenIndex.get(parsed.needle) ?? []) {
- results.push({
- id: resultId("resistor", resistor.reference),
- type: "resistor",
- reference: resistor.reference,
- pinNumber: null,
- touchpoint: null,
- resistor,
- pin: null,
- matchedField: "value",
- score: resistor.assembly_status === "not_fitted" ? 1100 : 1300,
- assemblyStatus: resistor.assembly_status || "unknown",
- notFitted: resistor.assembly_status === "not_fitted",
- });
- }
- for (const conflict of index.evidenceConflicts) {
- const hay = normalized([
- conflict.subject_reference,
- conflict.summary,
- ...(conflict.claims || []).map((claim) => JSON.stringify(claim)),
- ].join(" "));
- if (hay.includes(parsed.needle) && conflict.status === "unresolved") {
- results.push({
- id: resultId("evidence_conflict", conflict.subject_reference || conflict.id),
- type: "evidence_conflict",
- reference: conflict.subject_reference || conflict.id,
- pinNumber: null,
- touchpoint: null,
- resistor: index.resistorByReference.get(conflict.subject_reference) || null,
- pin: null,
- matchedField: "evidence_conflict",
- score: 200,
- evidenceConflict: conflict,
- });
- }
- }
- return sortResults(results);
- }
- /** Compatibility: touchpoint pins only (does not include resistor pads). */
- export function sameNetPins(data, net) {
- const wanted = text(net);
- if (!wanted) return [];
- const matches = [];
- for (const touchpoint of data?.touchpoints ?? []) {
- for (const pin of touchpoint.pins ?? []) {
- if (pin.net === wanted) {
- matches.push({
- kind: "touchpoint",
- reference: touchpoint.reference,
- pinNumber: text(pin.number),
- touchpoint,
- resistor: null,
- pin,
- });
- }
- }
- }
- return matches.sort((left, right) => {
- const referenceOrder = naturalCompare(left.reference, right.reference);
- return referenceOrder || naturalCompare(left.pinNumber, right.pinNumber);
- });
- }
- /** Touchpoint pins + resistor pads sharing the PCB net. */
- export function sameNetMembers(data, net) {
- const wanted = text(net);
- if (!wanted) return [];
- const index = buildBoardIndex(data);
- const members = index.netMembers.get(wanted) || [];
- if (members.length) return members.map((item) => ({...item}));
- // Case-insensitive fallback
- for (const [name, rows] of index.netMembers.entries()) {
- if (normalized(name) === normalized(wanted)) {
- return rows.map((item) => ({...item}));
- }
- }
- return [];
- }
- export function extractPathResistors(data, ...texts) {
- const index = new Map((data?.resistors ?? []).map((item) => [text(item.reference), item]));
- const ordered = [];
- const seen = new Set();
- for (const value of texts) {
- const chunks = Array.isArray(value) ? value : [value];
- for (const chunk of chunks) {
- const source = text(chunk);
- if (!source) continue;
- ANNOTATION_RESISTOR.lastIndex = 0;
- let match;
- while ((match = ANNOTATION_RESISTOR.exec(source))) {
- const reference = `R${match[1]}`;
- if (seen.has(reference)) continue;
- seen.add(reference);
- const resistor = index.get(reference);
- if (!resistor) {
- throw new Error(`annotation resistor ${reference} missing from resistor index`);
- }
- ordered.push(resistor);
- }
- }
- }
- return ordered;
- }
- export function findCandidates(data, capability) {
- const wanted = normalized(capability);
- if (!wanted) return [];
- const acceptedCapabilities = new Set(
- (CAPABILITY_ALIASES[wanted] ?? [wanted]).map(normalized),
- );
- const candidates = [];
- for (const touchpoint of data?.touchpoints ?? []) {
- for (const pin of touchpoint.pins ?? []) {
- const pinCapabilities = capabilities(pin).map(normalized);
- if (!pinCapabilities.some((item) => acceptedCapabilities.has(item))) continue;
- if (wanted === "gpio" && !["gpio", "direct_gpio"].includes(normalized(pin.function_category))) {
- continue;
- }
- if (baseBlockers(pin).length) continue;
- const purpose = text(pin.summary).trim();
- const polarity = normalized(pin.polarity);
- const details = [];
- if (purpose) details.push(`用途 ${purpose}`);
- if (polarity && polarity !== "unknown") details.push(`极性 ${pin.polarity}`);
- candidates.push({
- reference: touchpoint.reference,
- touchpoint,
- pin,
- reason: `${details.length ? `${details.join(";")};` : ""}能力 ${capability} 匹配;已验证 FPGA 路径至 ${pin.fpga.ball};外部电平 ${pin.external_level}。`,
- warning: "只证明物理可用性,仍需检查当前工程约束冲突。",
- });
- }
- }
- return candidates.sort((left, right) => {
- const categoryMatchLeft = normalized(left.pin.function_category) === wanted ? 1 : 0;
- const categoryMatchRight = normalized(right.pin.function_category) === wanted ? 1 : 0;
- if (categoryMatchRight !== categoryMatchLeft) return categoryMatchRight - categoryMatchLeft;
- const referenceOrder = naturalCompare(left.reference, right.reference);
- return referenceOrder || naturalCompare(left.pin.number, right.pin.number);
- });
- }
- export function isValidRtlPortName(name) {
- return RTL_PORT.test(text(name));
- }
- /** Back SVG export uses KiCad --mirror about the vertical/Y axis (left-right flip). */
- export const BACK_MIRROR_AXIS = "y";
- export function mirrorBoardX(x, boardWidth) {
- const width = Number(boardWidth);
- const value = Number(x);
- if (!Number.isFinite(width) || !Number.isFinite(value)) return value;
- return width - value;
- }
- export function displayPoint(point, boardWidth, viewingSide) {
- const x = Number(point?.x);
- const y = Number(point?.y);
- if (viewingSide !== "back") return {x, y};
- return {x: mirrorBoardX(x, boardWidth), y};
- }
- export function displayBounds(bounds, boardWidth, viewingSide) {
- const x = Number(bounds?.x);
- const y = Number(bounds?.y);
- const width = Number(bounds?.width);
- const height = Number(bounds?.height);
- if (viewingSide !== "back") {
- return {x, y, width, height};
- }
- return {
- x: mirrorBoardX(x + width, boardWidth),
- y,
- width,
- height,
- };
- }
- export function itemVisibleOnSide(item, viewingSide) {
- return (item?.side || "front") === viewingSide;
- }
- export function generateAdcSnippet(pin, rtlPortName, runtimeStatus = {}) {
- if (runtimeStatus.adcCopyEnabled !== true) {
- throw new Error("源数据已过期,ADC 复制已关闭。");
- }
- if (!isValidRtlPortName(rtlPortName)) {
- throw new Error("生成 ADC 前请输入合法的 RTL 端口名。");
- }
- if (baseBlockers(pin).length) {
- throw new Error("此针脚不具备 ADC 生成资格。");
- }
- const ball = text(pin.fpga.ball);
- const ioStandard = text(pin.fpga.io_standard);
- if (!/^[A-Z]+[0-9]+$/.test(ball) || !/^[A-Za-z0-9_.+-]+$/.test(ioStandard)) {
- throw new Error("已验证 FPGA 分配包含不安全的 ADC 值。");
- }
- const assignments = [`LOCATION = ${ball}`, `IOSTANDARD = ${ioStandard}`];
- if (pin.adc_pulltype != null) {
- const pulltype = text(pin.adc_pulltype);
- if (!/^[A-Z][A-Z0-9_]*$/.test(pulltype)) {
- throw new Error("人工注释的 PULLTYPE 包含不安全值。");
- }
- assignments.push(`PULLTYPE = ${pulltype}`);
- }
- return `set_pin_assignment { ${rtlPortName} } { ${assignments.join("; ")}; }`;
- }
|