← Commit history
0.2.137: footprints checked against their datasheets' dimensions (part-check dims, Altium dimensions and pictures, design review section)
13 files changed
+468−22
Cargo.lock+11−11Cargo.toml+1−1crates/adom-aiflow/src/main.rs+21−7crates/adom-aiflow/src/page_results.rs+58crates/adom-aiflow/src/part_check.rs+105docs/altium-lane.md+4docs/release-0.2.137.md+21package.json+1−1page.json+1−1skills/aiflow-sourcing/SKILL.md+9tests/altium-dims.py+73tools/altium-dims.py+132tools/altium-project.py+31−1Cargo.lock+11−11@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-sys", "roxmltree",@@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "serde",@@ -79,7 +79,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-board", "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.136"+version = "0.2.137" dependencies = [ "aiflow-sys", "serde",@@ -120,7 +120,7 @@ dependencies = [ [[package]] name = "aiflow-sys"-version = "0.2.136"+version = "0.2.137" dependencies = [ "serde_json", ]
Cargo.toml+1−1@@ -15,7 +15,7 @@ members = [ ] [workspace.package]-version = "0.2.136"+version = "0.2.137" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
crates/adom-aiflow/src/main.rs+21−7@@ -2982,7 +2982,10 @@ fn page_results_cmd(r: &mut Run, dir: &Path, page: &str, out: Option<&str>, page // the run report's folder, when it lives on this same page (page-root relative) let run_link = pagedir::run_page(&r.data).filter(|(p, _)| !in_package && Some(p) == page.as_ref()).map(|(_, d)| format!("{}/", pagedir::run_rel(d.as_deref(), &report_id(r)))); let when = now();- let built = page_results::build(&r.data, &figures, board.as_ref().map(|b| (board_path.as_str(), b)), &sha, bom.as_deref(), run_link.as_deref(), molecule, &root, pd, &when).unwrap_or_else(|e| err(&format!("design review: {e}"), &[]));+ // the Altium lane's dimensioned footprints (altium/footprint-dims.json) for the review's datasheet cross-check+ let mut page_data = r.data.clone();+ if let Some(v) = std::fs::read(dir.join("altium/footprint-dims.json")).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) { page_data["altiumFootprintDims"] = v; }+ let built = page_results::build(&page_data, &figures, board.as_ref().map(|b| (board_path.as_str(), b)), &sha, bom.as_deref(), run_link.as_deref(), molecule, &root, pd, &when).unwrap_or_else(|e| err(&format!("design review: {e}"), &[])); r.outcome("page-results", page_results::outcome(&built, &board_path, &sha, &root, page.as_deref(), &when)); r.save().unwrap_or_else(|e| err(&e, &[])); let mut hints: Vec<String> = Vec::new();@@ -5148,33 +5151,44 @@ fn main() { Some(String::from_utf8_lossy(&o.stdout).to_string()) }; let (mut results, mut lines) = (Vec::new(), Vec::new());+ let mut dim_stops: Vec<String> = Vec::new(); for f in &facts { let mpn = f["mpn"].as_str().unwrap_or(""); let row = rows.iter().find(|x| x["mpn"].as_str().is_some_and(|m| m.eq_ignore_ascii_case(mpn))).cloned().unwrap_or(Value::Null); let bom_maker = row["manufacturer"].as_str().map(str::to_string);- let (what, pads, height, maker) = if row["projectLib"].is_object() {+ let (what, fp_text, height, maker) = if row["projectLib"].is_object() { let pl = &row["projectLib"];- let pads = pl["footprintFile"].as_str().and_then(|p| std::fs::read_to_string(p).ok()).map(|t| part_check::footprint_pads(&t)).unwrap_or_default();+ let pads = pl["footprintFile"].as_str().and_then(|p| std::fs::read_to_string(p).ok()); let h = pl["model"].as_str().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| part_check::step_height(&t)); ("the project library".to_string(), pads, h, pl["provenance"]["manufacturer"].as_str().map(str::to_string)) } else if let Some(page) = row["wiki"].as_str().or(f["page"].as_str()) { let pj = wiki_page_json(page).unwrap_or(Value::Null); let parts = &pj["component"]["parts"];- let pads = parts["footprint"].as_str().and_then(|fp| wiki_file(page, fp)).map(|t| part_check::footprint_pads(&t)).unwrap_or_default();+ let pads = parts["footprint"].as_str().and_then(|fp| wiki_file(page, fp)); let h = parts["step"].as_str().and_then(|st| wiki_file(page, st)).and_then(|t| part_check::step_height(&t)); (page.to_string(), pads, h, pj["component"]["manufacturer"].as_str().map(str::to_string)) } else { lines.push(format!("{mpn}: not in the parts record and no \"page\" given: nothing to compare (run `parts` first)")); continue; };- let (v, fl) = part_check::compare(f, &what, &pads, height, maker.as_deref(), bom_maker.as_deref());+ let pads = fp_text.as_deref().map(part_check::footprint_pads).unwrap_or_default();+ let (mut v, fl) = part_check::compare(f, &what, &pads, height, maker.as_deref(), bom_maker.as_deref());+ // the datasheet's key distances on the footprint (pitch, span, body): a mismatch stops unless acknowledged+ let (drows, dstop, dacked) = part_check::dims(f, &what, &pads, fp_text.as_deref().and_then(part_check::fab_box));+ if !drows.is_empty() { v["dims"] = json!(drows); v["pass"] = json!(v["pass"] == true && dstop.is_empty()); } results.push(v); lines.extend(fl);+ dim_stops.extend(dstop);+ lines.extend(dacked); } let checked: Vec<String> = facts.iter().filter_map(|f| f["mpn"].as_str().map(|m| m.to_ascii_uppercase())).collect(); let unchecked: Vec<String> = rows.iter().filter(|x| x["wiki"].is_string() || x["projectLib"].is_object()).filter_map(|x| x["mpn"].as_str()).filter(|m| !checked.contains(&m.to_ascii_uppercase())).map(str::to_string).collect();- r.outcome("part-check", json!({"file": aiflow_sys::canonicalize(file).map(|p| p.display().to_string()).unwrap_or(file.clone()), "parts": results, "findings": lines, "unchecked": unchecked}));+ r.outcome("part-check", json!({"file": aiflow_sys::canonicalize(file).map(|p| p.display().to_string()).unwrap_or(file.clone()), "parts": results, "findings": lines, "dimensionMismatches": dim_stops, "unchecked": unchecked})); r.save().unwrap();+ if !dim_stops.is_empty() {+ err(&format!("a footprint disagrees with its datasheet's dimensions (a wrong footprint is a wrong board):\n {}", dim_stops.join("\n ")),+ &["Check the drawing again. When the datasheet is right, fix the footprint (its page when it is yours, or open an issue on it) or give the part from the project library with \"prefer\": true; when the difference is fine (a nominal body drawn against a maximum), add \"ack\": \"<why>\" to that dimension in the part-checks file.".into()]);+ } let tail = if unchecked.is_empty() { String::new() } else { format!("\nnot checked yet ({}): {}", unchecked.len(), unchecked.iter().take(20).cloned().collect::<Vec<_>>().join(", ")) }; let hints = vec!["A page that is wrong: fix it when it is yours, or open an issue on it with what the datasheet says (never edit someone else's page); meanwhile give the part from the project library with \"prefer\": true (aiflow-sourcing).".to_string()]; if !lines.is_empty() { findings(&format!("{} part(s) checked against their datasheets; what disagrees:\n {}{tail}", results.len(), lines.join("\n ")), &hints); }@@ -5955,7 +5969,7 @@ fn main() { // the lane's pure helpers (tools/altium-lane.py: the symbol check, project-library parts), then the Altium half let run = Run::open(&dir); let target = target.clone().or_else(|| run.as_ref().and_then(|r| r.data["target"].as_str().map(str::to_string))).or_else(|| std::env::var("AIFLOW_TARGET").ok()).unwrap_or_default();- let script = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-spice.py"), include_str!("../../../tools/altium-sim.py"), include_str!("../../../tools/altium-libfix.py"), include_str!("../../../tools/altium-project.py"));+ let script = format!("{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-spice.py"), include_str!("../../../tools/altium-sim.py"), include_str!("../../../tools/altium-libfix.py"), include_str!("../../../tools/altium-dims.py"), include_str!("../../../tools/altium-project.py")); let status = aiflow_sys::process::Command::new("python3").arg(lane_script("altium", &script)).args(args) .env("AIFLOW_RUN", &dir).env("AIFLOW_TARGET", &target).env("AIFLOW_THREAD", thread(&cli)).env("AIFLOW_EXE", std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default()) .status().unwrap_or_else(|e| err(&format!("altium steps need python3: {e}"), &[]));
crates/adom-aiflow/src/page_results.rs+58@@ -235,6 +235,40 @@ pub fn build(data: &Value, figures: &[(String, String, String)], board: Option<( md.push('\n'); open.push("chip images on the components table are not added by the binary yet: each part's wiki page carries its hero".into()); }+ // the datasheet cross-check (0.2.137): each footprint's key distances against its datasheet, from `part-check` and+ // from Altium's dimensioned footprints (altium/footprint-dims.json, handed in as `altiumFootprintDims`)+ let mut checked: Vec<(String, String, Vec<Value>, Option<String>)> = Vec::new();+ for p in o["part-check"]["parts"].as_array().into_iter().flatten() {+ if let Some(d) = p["dims"].as_array().filter(|d| !d.is_empty()) { checked.push((p["mpn"].as_str().unwrap_or("?").into(), p["checked"].as_str().unwrap_or("").into(), d.clone(), None)); }+ }+ for p in data["altiumFootprintDims"].as_array().into_iter().flatten() {+ if let Some(d) = p["rows"].as_array().filter(|d| !d.is_empty()) {+ checked.push((p["mpn"].as_str().unwrap_or("?").into(), format!("Altium footprint {}", p["footprint"].as_str().unwrap_or("?")), d.clone(), p["image"].as_str().map(str::to_string)));+ }+ }+ if !checked.is_empty() {+ sections.push("footprints");+ md.push_str("## Footprints checked against datasheets\n\nEach footprint's key distances (pad pitch and span, body size) measured on the footprint the board uses and compared with the manufacturer's drawing.\n\n| Part | Footprint checked | Dimension | Datasheet (mm) | Footprint (mm) | Result |\n|---|---|---|---|---|---|\n");+ let mut pics = String::new();+ for (mpn, what, rows, image) in &checked {+ for d in rows {+ let ok = d["pass"] == true || d["check"] == "MATCH";+ let result = if ok { "match".to_string() } else if let Some(a) = d["ack"].as_str() { format!("differs, acknowledged: {}", esc(a)) } else { "**differs**".to_string() };+ let num = |v: &Value| v.as_f64().map(|x| format!("{x:.3}")).unwrap_or_else(|| "?".into());+ md.push_str(&format!("| {} | {} | {} ({} to {}) | {} | {} | {} |\n", esc(mpn), esc(what), esc(d["what"].as_str().unwrap_or("")), esc(d["a"].as_str().unwrap_or("")), esc(d["b"].as_str().unwrap_or("")), num(&d["datasheetMm"]), num(&d["footprintMm"]), result));+ }+ if let Some(src) = image.as_deref().map(Path::new).filter(|s| s.is_file()) {+ let name = format!("footprint-{}", src.file_name().and_then(|n| n.to_str()).unwrap_or("footprint.png"));+ if std::fs::copy(src, dir.join(&name)).is_ok() {+ let rel = format!("{rel_dir}/{name}");+ pics.push_str(&format!("\n\n*{}: {} with its datasheet dimensions*\n\n", esc(mpn), esc(mpn), esc(what)));+ files.push(rel);+ }+ }+ }+ md.push('\n');+ md.push_str(&pics);+ } open.push("the interactive schematic (circuit explorer, #131) is not generated by the binary yet: link the schematic PDF or a block diagram from this review by hand".into()); let readme = format!("{rel_dir}/README.md"); std::fs::write(out_root.join(&readme), md).map_err(|e| format!("{readme}: {e}"))?;@@ -321,6 +355,30 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp); } + #[test]+ fn footprints_checked_against_datasheets_are_tabled_with_their_pictures() {+ let tmp = aiflow_sys::temp_dir().join(format!("aiflow-page-dims-{}", aiflow_sys::process::id()));+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).unwrap();+ let pic = tmp.join("SOIC8.png");+ std::fs::write(&pic, b"png").unwrap();+ let data = json!({+ "outcomes": {"part-check": {"parts": [{"mpn": "TPS54202", "checked": "adom/tps54202", "dims": [+ {"what": "span", "a": "1", "b": "6", "datasheetMm": 2.8, "footprintMm": 2.8, "pass": true},+ {"what": "body length", "a": "TL", "b": "BL", "datasheetMm": 3.0, "footprintMm": 2.9, "pass": false, "ack": "nominal against max"}]}]}},+ "altiumFootprintDims": [{"footprint": "SOIC8", "mpn": "NE555DR", "image": pic.display().to_string(),+ "rows": [{"what": "pitch", "a": "1", "b": "2", "datasheetMm": 1.27, "footprintMm": 1.27, "check": "MATCH"}]}]+ });+ let built = build(&data, &[], None, "0123456789abcdef", None, None, false, &tmp, None, "2026-12-02T12:00:00Z").unwrap();+ let md = std::fs::read_to_string(tmp.join("design-review/README.md")).unwrap();+ assert!(md.contains("## Footprints checked against datasheets"), "{md}");+ assert!(md.contains("| TPS54202 | adom/tps54202 | span (1 to 6) | 2.800 | 2.800 | match |"), "{md}");+ assert!(md.contains("| 2.900 | differs, acknowledged: nominal against max |"), "{md}");+ assert!(md.contains("| NE555DR | Altium footprint SOIC8 | pitch (1 to 2) | 1.270 | 1.270 | match |"), "{md}");+ assert!(md.contains("](design-review/footprint-SOIC8.png)") && tmp.join("design-review/footprint-SOIC8.png").is_file(), "{md}");+ assert!(built.sections.contains(&"footprints"));+ }+ #[test] fn a_page_from_another_board_is_an_open_item() { // issue #199: rev B delivered with rev A's figures on its page
crates/adom-aiflow/src/part_check.rs+105@@ -14,6 +14,19 @@ //! `land` is the maker's recommended land in the footprint's own frame (mm, y down, pad 1 where the footprint //! has it); give only the pads the datasheet dimensions. Findings are suggestions: fix the page (or open an issue //! on it when it is not yours), or give the part from the project library with `"prefer": true`.+//!+//! `dims` (the datasheet cross-check, 0.2.137) are the package's key distances the way the datasheet drawing gives+//! them, each between two pads (their centres) or two corners of the body (`TL`, `TR`, `BR`, `BL` of the footprint's+//! assembly outline on F.Fab):+//!+//! ```json+//! "dims": [{"what": "span", "a": "1", "b": "8", "mm": 5.4}, {"what": "pitch", "a": "1", "b": "2", "mm": 1.27},+//! {"what": "body width", "a": "TL", "b": "TR", "mm": 3.9}]+//! ```+//!+//! `axis` ("x" or "y") measures along one axis only (the centre-to-centre span of two staggered pads), else the+//! straight distance; `tolMm` defaults to 0.05. A dimension that disagrees is the one finding that stops: a wrong+//! footprint is a wrong board. `"ack": "<why>"` on the dimension keeps it reported and lets the check pass. use aiflow_board::sx; use serde_json::{json, Value}; @@ -39,6 +52,69 @@ pub fn footprint_pads(text: &str) -> Vec<Pad> { }).collect() } +/// The box of a footprint's assembly outline (F.Fab lines, rectangles, arcs' ends and polygons), in its own frame:+/// (x0, y0, x1, y1), y down. None when it has no F.Fab graphics.+pub fn fab_box(text: &str) -> Option<(f64, f64, f64, f64)> {+ let root = sx::parse(text).ok()?;+ let mut pts: Vec<(f64, f64)> = Vec::new();+ for kind in ["fp_line", "fp_rect", "fp_arc", "fp_poly"] {+ for g in root.find_all(kind) {+ if g.find("layer").and_then(|l| l.atom(1)) != Some("F.Fab") { continue; }+ for key in ["start", "end", "mid"] {+ if let Some(n) = g.find(key) { if let (Some(x), Some(y)) = (n.number(1), n.number(2)) { pts.push((x, y)); } }+ }+ if let Some(ps) = g.find("pts") { for xy in ps.find_all("xy") { if let (Some(x), Some(y)) = (xy.number(1), xy.number(2)) { pts.push((x, y)); } } }+ }+ }+ if pts.is_empty() { return None; }+ let x0 = pts.iter().map(|p| p.0).fold(f64::MAX, f64::min);+ let y0 = pts.iter().map(|p| p.1).fold(f64::MAX, f64::min);+ let x1 = pts.iter().map(|p| p.0).fold(f64::MIN, f64::max);+ let y1 = pts.iter().map(|p| p.1).fold(f64::MIN, f64::max);+ Some((x0, y0, x1, y1))+}++/// A dimension end: a pad number (its centre; a repeated number is its first pad) or a body corner of `fab`.+fn end_point(name: &str, pads: &[Pad], fab: Option<(f64, f64, f64, f64)>) -> Result<(f64, f64), String> {+ let corner = |b: (f64, f64, f64, f64)| match name { "TL" => Some((b.0, b.1)), "TR" => Some((b.2, b.1)), "BR" => Some((b.2, b.3)), "BL" => Some((b.0, b.3)), _ => None };+ if ["TL", "TR", "BR", "BL"].contains(&name) {+ return fab.and_then(corner).ok_or_else(|| format!("the footprint has no assembly outline (F.Fab) for the body corner {name}"));+ }+ pads.iter().find(|p| p.num == name).map(|p| (p.x, p.y)).ok_or_else(|| format!("the footprint has no pad {name}"))+}++/// The datasheet's `dims` measured on the footprint: one row each {what, a, b, datasheetMm, footprintMm, pass, ack},+/// the mismatches that stop, and the acknowledged ones.+pub fn dims(facts: &Value, what: &str, pads: &[Pad], fab: Option<(f64, f64, f64, f64)>) -> (Vec<Value>, Vec<String>, Vec<String>) {+ let mpn = facts["mpn"].as_str().unwrap_or("?");+ let (mut rows, mut stop, mut acked) = (Vec::new(), Vec::new(), Vec::new());+ let name = |v: &Value| v.as_str().map(str::to_string).or_else(|| v.as_u64().map(|x| x.to_string())).unwrap_or_default();+ for d in facts["dims"].as_array().into_iter().flatten() {+ let (a, b) = (name(&d["a"]), name(&d["b"]));+ let label = d["what"].as_str().map(str::to_string).unwrap_or_else(|| format!("{a} to {b}"));+ let Some(want) = d["mm"].as_f64() else { stop.push(format!("{mpn}: dimension \"{label}\" has no \"mm\" (the datasheet's value)")); continue };+ let tol = d["tolMm"].as_f64().unwrap_or(POS_TOL);+ let measured = end_point(&a, pads, fab).and_then(|p| end_point(&b, pads, fab).map(|q| (p, q))).map(|(p, q)| match d["axis"].as_str() {+ Some("x") => (p.0 - q.0).abs(),+ Some("y") => (p.1 - q.1).abs(),+ _ => ((p.0 - q.0).powi(2) + (p.1 - q.1).powi(2)).sqrt(),+ });+ let ack = d["ack"].as_str().filter(|s| !s.trim().is_empty()).map(str::to_string);+ match measured {+ Ok(m) => {+ let pass = (m - want).abs() <= tol;+ rows.push(json!({"what": label, "a": a, "b": b, "datasheetMm": want, "footprintMm": (m * 1000.0).round() / 1000.0, "pass": pass, "ack": ack}));+ if !pass {+ let line = format!("{mpn}: {label} ({a} to {b}) is {m:.3} mm on the footprint of {what}, {want:.3} mm in the datasheet");+ match &ack { Some(w) => acked.push(format!("{line} (acknowledged: {w})")), None => stop.push(line) }+ }+ }+ Err(e) => { rows.push(json!({"what": label, "a": a, "b": b, "datasheetMm": want, "pass": false, "error": e})); stop.push(format!("{mpn}: {label}: {e}")); }+ }+ }+ (rows, stop, acked)+}+ /// The height of a STEP model: the spread of its points' z (mm), when it has any. pub fn step_height(text: &str) -> Option<f64> { let mut lo = f64::MAX;@@ -120,6 +196,35 @@ mod tests { (pad "1" smd roundrect (at -2.9 0) (size 1.5 3.4) (layers "F.Cu")) (pad "2" smd roundrect (at 2.9 0 90) (size 3.4 1.5) (layers "F.Cu")))"#; + #[test]+ fn the_datasheet_dimensions_are_measured_on_the_footprint() {+ // a SOIC-8: pads 1-4 on the left at x -2.7, 5-8 on the right at x 2.7, 1.27 mm pitch; body 3.9 x 4.9 on F.Fab+ let mut fp = String::from("(footprint \"SOIC8\" (layer \"F.Cu\")");+ for i in 0..4 { let y = -1.905 + 1.27 * i as f64; fp += &format!("(pad \"{}\" smd rect (at -2.7 {y}) (size 1.55 0.6) (layers \"F.Cu\"))(pad \"{}\" smd rect (at 2.7 {y}) (size 1.55 0.6) (layers \"F.Cu\"))", i + 1, 8 - i); }+ fp += "(fp_line (start -1.95 -2.45) (end 1.95 -2.45) (layer \"F.Fab\"))(fp_line (start 1.95 -2.45) (end 1.95 2.45) (layer \"F.Fab\"))(fp_line (start 1.95 2.45) (end -1.95 2.45) (layer \"F.Fab\"))(fp_line (start -1.95 2.45) (end -1.95 -2.45) (layer \"F.Fab\")))";+ let pads = footprint_pads(&fp);+ let fab = fab_box(&fp);+ assert_eq!(fab, Some((-1.95, -2.45, 1.95, 2.45)));+ let facts = json!({"mpn": "X", "dims": [{"what": "span", "a": "1", "b": "8", "mm": 5.4}, {"what": "pitch", "a": 1, "b": 2, "mm": 1.27},+ {"what": "body width", "a": "TL", "b": "TR", "mm": 3.9}, {"what": "body length", "a": "TL", "b": "BL", "mm": 5.0}]});+ let (rows, stop, acked) = dims(&facts, "adom/soic8", &pads, fab);+ assert_eq!(rows.len(), 4);+ assert!(rows[..3].iter().all(|r| r["pass"] == true), "{rows:?}");+ assert_eq!(stop, vec!["X: body length (TL to BL) is 4.900 mm on the footprint of adom/soic8, 5.000 mm in the datasheet".to_string()]);+ assert!(acked.is_empty());+ // acknowledged: reported, does not stop+ let ackd = json!({"mpn": "X", "dims": [{"what": "body length", "a": "TL", "b": "BL", "mm": 5.0, "ack": "the page draws the nominal body; 5.0 is the max"}]});+ let (_, stop, acked) = dims(&ackd, "adom/soic8", &pads, fab);+ assert!(stop.is_empty() && acked[0].contains("acknowledged: the page draws"), "{acked:?}");+ // along one axis; a pad or an outline that is not there stops with why+ let axis = json!({"mpn": "X", "dims": [{"what": "row offset", "a": "1", "b": "7", "axis": "y", "mm": 1.27}, {"a": "1", "b": "9", "mm": 1.0}]});+ let (rows, stop, _) = dims(&axis, "p", &pads, None);+ assert_eq!(rows[0]["pass"], true);+ assert!(stop[0].contains("no pad 9"), "{stop:?}");+ let (_, stop, _) = dims(&json!({"mpn": "X", "dims": [{"a": "TL", "b": "TR", "mm": 3.9}]}), "p", &pads, None);+ assert!(stop[0].contains("no assembly outline"), "{stop:?}");+ }+ #[test] fn reads_pads_and_a_step_height() { let p = footprint_pads(FP);
docs/altium-lane.md+4@@ -184,3 +184,7 @@ From altium-bridge 0.2.120 the layer count comes from the bridge (`altium_layer_ After the library step imports footprints, `altium_check_silkscreen` measures each one's silkscreen against its exposed copper: the pad plus its solder mask opening (the pad's own, else Altium's default 4 mil). Footprints closer than spec `silkPadClearance` (default 0.15 mm, JLCPCB's figure) are named in the step's result with the clearance and the pad, as a note: the fab clips silkscreen out of a pad opening, so such a line prints shorter rather than on the pad. Trim it with `altium_edit_footprint` where the outline matters. A KiCad 0603 resistor footprint reads about 0.06 mm with the 4 mil opening. +## Footprints checked against their datasheets (altium-bridge 0.2.121)++When `design/part-checks.json` gives a part's `dims` (pitch, span, body size between pads or body corners; the aiflow-sourcing skill), `altium library` puts each on the imported footprint with `altium_add_dimensions`: a real Altium dimension anchored to the pads or the assembly outline's corners, its direction and position worked out from the footprint's KiCad file, text scaled to the footprint. Altium answers MATCH or MISMATCH for each. A mismatch stops the step (the library is built; fix the footprint or acknowledge the dimension with `"ack"`). The dimensioned footprint is pictured (`altium/footprints/<footprint>.png`) and recorded in `altium/footprint-dims.json`, which the design review shows under "Footprints checked against datasheets".+
docs/release-0.2.137.mdadded+21@@ -0,0 +1,21 @@+# adom-aiflow 0.2.137++## Footprints checked against their datasheets' dimensions++A footprint can have the right name and the wrong size. `design/part-checks.json` (the facts the AI reads from each datasheet, `part-check`) now takes the package's key distances:++```json+"dims": [{"what": "span", "a": "1", "b": "8", "mm": 5.4}, {"what": "pitch", "a": "1", "b": "2", "mm": 1.27},+ {"what": "body width", "a": "TL", "b": "TR", "mm": 3.9}]+```++Each is between two pads (their centres) or two corners of the body (`TL`, `TR`, `BR`, `BL` of the footprint's assembly outline on F.Fab), along one `axis` or straight; `tolMm` defaults to 0.05.++- `part-check` measures every dimension on the footprint the board uses (the wiki page's or the project library's), on every lane. A dimension that disagrees is the one finding that stops, since a wrong footprint is a wrong board; `"ack": "<why>"` on that dimension reports it and lets it pass.+- Altium (altium-bridge 0.2.121): `altium library` puts the same dimensions on each imported footprint as real Altium dimensions anchored to its pads and outline corners (direction and position worked out from the footprint, text scaled to it), Altium answers MATCH or MISMATCH, a mismatch stops the step, and the dimensioned footprint is pictured (`altium/footprints/`) and recorded (`altium/footprint-dims.json`). A footprint is dimensioned once: a rerun does not add copies.+- The design review (`project-page --results`) has a new section, "Footprints checked against datasheets": each dimension, the datasheet's value, the footprint's, and the result, with the Altium pictures.+- The aiflow-sourcing skill and docs/altium-lane.md say how to write the dimensions.++Tested live on the test desktop (Altium Designer 26, altium-bridge 0.2.121): an 0603 resistor's pad centres, body length and body width matched in Altium and the picture was kept; a rerun did not dimension it again. Unit tests cover the measuring, the outline (a silkscreen line is not the body), the refusals and the review section.++Known: the dimension arrows keep Altium's default size, which is large on a small part; the text is scaled. altium-lane is confirming the option names for the arrows.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.136",+ "version": "0.2.137", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.136",+ "version": "0.2.137", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/aiflow-sourcing/SKILL.md+9@@ -206,6 +206,15 @@ A page `parts` matched by MPN is a page with the right name, not proof that its `land` is the maker's recommended land in the footprint's own frame (mm, y down, pad 1 where the footprint has it); give the pads the datasheet dimensions, including the thermal pad. Then `adom-aiflow part-check`: it reads the footprint and the STEP the board will use (the wiki page's, or the project library's) and reports each pad whose centre or size is more than 0.05 mm off, a model more than 0.05 mm outside the datasheet's body height, and a page or BOM naming another maker. A finding: fix the page when it is yours; otherwise open an issue on it with what the datasheet says, and give the part from the project library with `"prefer": true` meanwhile. `finish` lists the findings, and notes the parts never checked. +**The package's key distances (`dims`, 0.2.137).** Add the distances the datasheet's package drawing gives, each between two pads (their centres) or two corners of the body (`TL`, `TR`, `BR`, `BL` of the footprint's assembly outline):++```json+"dims": [{"what": "span", "a": "1", "b": "8", "mm": 5.4}, {"what": "pitch", "a": "1", "b": "2", "mm": 1.27},+ {"what": "body width", "a": "TL", "b": "TR", "mm": 3.9}]+```++`axis` ("x" or "y") measures along one axis only; `tolMm` defaults to 0.05. `part-check` measures each on the footprint the board uses, and a dimension that disagrees is the one finding that stops: a wrong footprint is a wrong board. When the difference is fine (a nominal body drawn against a maximum), add `"ack": "<why>"` to that dimension. On the Altium lane, `altium library` puts the same dimensions on each imported footprint as real anchored Altium dimensions (altium-bridge 0.2.121), checks them there, and keeps a picture of each; the design review (`project-page --results`) tables every dimension and shows the pictures.+ ## Parts with no public component page yet When a part's page must stay private, waits for an owner's sign-off, or the footprint is a reviewed project-only one, give it from the board's project library: `adom-aiflow parts --project-lib <dir>` (or `"projectLib": "<dir>"` in the spec or requirements). The folder holds the KiCad symbols (`*.kicad_sym`), footprints (`*.pretty/*.kicad_mod`), STEP models and a `provenance.json`:
tests/altium-dims.pyadded+73@@ -0,0 +1,73 @@+"""tools/altium-dims.py without Altium: the footprint's geometry, the dimensions asked of the bridge and its answers.+ python3 tests/altium-dims.py"""+import json, re, tempfile+from pathlib import Path++TOOLS = Path(__file__).resolve().parent.parent / 'tools'++SOIC = '(footprint "SOIC8" (layer "F.Cu")\n (fp_line (start -0.5 -3.1) (end 0.5 -3.1) (stroke (width 0.12) (type solid)) (layer "F.SilkS"))\n' + ''.join(+ ' (pad "%d" smd rect (at -2.7 %.3f) (size 1.55 0.6) (layers "F.Cu"))\n (pad "%d" smd rect (at 2.7 %.3f) (size 1.55 0.6) (layers "F.Cu"))\n' % (i + 1, -1.905 + 1.27 * i, 8 - i, -1.905 + 1.27 * i) for i in range(4)) + \+ ' (fp_line (start -1.95 -2.45) (end 1.95 -2.45) (stroke (width 0.1) (type solid)) (layer "F.Fab"))\n' \+ ' (fp_line (start 1.95 -2.45) (end 1.95 2.45) (stroke (width 0.1) (type solid)) (layer "F.Fab"))\n' \+ ' (fp_line (start 1.95 2.45) (end -1.95 2.45) (stroke (width 0.1) (type solid)) (layer "F.Fab"))\n' \+ ' (fp_line (start -1.95 2.45) (end -1.95 -2.45) (stroke (width 0.1) (type solid)) (layer "F.Fab"))\n' \+ ' (fp_line (start -3.7 -2.7) (end 3.7 -2.7) (stroke (width 0.05) (type solid)) (layer "F.CrtYd")))\n'+++def harness(answers):+ calls = []+ tmp = Path(tempfile.mkdtemp(prefix='aiflow-dims-'))+ def ab(verb, args, timeout=600):+ calls.append((verb, args))+ if verb == 'altium_add_dimensions':+ return {'success': True, 'dimensions': [dict(a, valueMm=answers.get((a['a'], a['b']), a['expect']), check='MATCH' if abs(answers.get((a['a'], a['b']), a['expect']) - a['expect']) <= a['toleranceMm'] else 'MISMATCH') for a in args['dimensions']]}+ if verb == 'altium_show_footprint':+ return {'success': True, 'shot': {'image': 'iVBORw0KGgo='}}+ return {'success': True}+ ns = {'re': re, 'json': json, 'Path': Path, 'ab': ab, 'win': lambda p: p.replace('/', '\\'), 'STATE': tmp, 'RUN': tmp / 'run'}+ exec((TOOLS / 'altium-dims.py').read_text(), ns)+ return ns, calls, tmp+++def main():+ ns, calls, tmp = harness({})+ pads, box = ns['kicad_geometry'](SOIC)+ assert pads['1'] == (-2.7, -1.905) and pads['8'] == (2.7, -1.905) and len(pads) == 8+ assert box == (-1.95, -2.45, 1.95, 2.45), box # the courtyard is not the body+ dims = [{'what': 'span', 'a': '1', 'b': '8', 'mm': 5.4}, {'what': 'pitch', 'a': '1', 'b': '2', 'mm': 1.27},+ {'what': 'body width', 'a': 'TL', 'b': 'TR', 'mm': 3.9}, {'what': 'body length', 'a': 'TL', 'b': 'BL', 'mm': 4.9},+ {'what': 'bad', 'a': '1', 'b': '9', 'mm': 1.0}]+ vd, problems = ns['verb_dims'](dims, pads, box)+ assert [d['dir'] for d in vd] == ['H', 'V', 'H', 'V'], vd+ assert problems == ['bad: no pad 9']+ # every dimension line runs outside the pads and the body, and two the same way go on opposite sides+ assert all(abs(d['at']) > (2.45 if d['dir'] == 'H' else 2.7) for d in vd) and vd[0]['at'] * vd[2]['at'] < 0, vd+ f = ns['dim_format'](pads, box)+ assert 0.25 <= f['textHeightMm'] <= 1.0 and f['units'] == 'mm'++ # all match: rows, no stop, the picture kept+ facts = {'mpn': 'X', 'source': 'ds p.1', 'dims': dims[:4]}+ rec = ns['dimension_part']('C:/L/P.PcbLib', 'SOIC8', facts, SOIC)+ assert rec['stop'] == [] and len(rec['rows']) == 4 and all(r['check'] == 'MATCH' for r in rec['rows'])+ assert rec['image'] and Path(rec['image']).name == 'SOIC8.png' and Path(rec['image']).is_file()+ assert [c[0] for c in calls] == ['altium_add_dimensions', 'altium_show_footprint']++ # a mismatch stops; an acknowledged one is reported only+ ns, _, _ = harness({('TL', 'BL'): 4.9})+ rec = ns['dimension_part']('C:/L/P.PcbLib', 'SOIC8', {'mpn': 'X', 'dims': [dims[0], {'what': 'body length', 'a': 'TL', 'b': 'BL', 'mm': 5.0}]}, SOIC)+ assert len(rec['stop']) == 1 and 'body length (TL to BL) is 4.9 mm on footprint SOIC8, 5.0 mm' in rec['stop'][0], rec['stop']+ ns, _, _ = harness({('TL', 'BL'): 4.9})+ rec = ns['dimension_part']('C:/L/P.PcbLib', 'SOIC8', {'mpn': 'X', 'dims': [{'what': 'body length', 'a': 'TL', 'b': 'BL', 'mm': 5.0, 'ack': 'nominal against max'}]}, SOIC)+ assert rec['stop'] == [] and 'acknowledged: nominal against max' in rec['acked'][0]++ # the record file keeps one entry per footprint+ ns, _, tmp = harness({})+ ns['save_dims_record']([{'footprint': 'A', 'rows': [1]}, {'footprint': 'B', 'rows': []}])+ ns['save_dims_record']([{'footprint': 'A', 'rows': [2]}])+ got = json.loads((tmp / 'footprint-dims.json').read_text())+ assert sorted(x['footprint'] for x in got) == ['A', 'B'] and [x for x in got if x['footprint'] == 'A'][0]['rows'] == [2]+ print('OK')+++if __name__ == '__main__':+ main()
tools/altium-dims.pyadded+132@@ -0,0 +1,132 @@+"""altium-dims: each footprint `altium library` imports, checked against its datasheet's dimensions in Altium and+pictured for the project page (altium-bridge 0.2.121, #43).++The datasheet facts are the ones `part-check` reads (design/part-checks.json): a part's `dims`, each between two pads+or two body corners (TL, TR, BR, BL of the assembly outline), with the datasheet's value in mm:++ {"parts": [{"mpn": "RC0603FR-0710KL", "source": "datasheet rev 2 p. 3", "dims": [+ {"what": "pad centres", "a": "1", "b": "2", "mm": 1.65}, {"what": "body length", "a": "TL", "b": "TR", "mm": 1.6}]}]}++`altium_add_dimensions` puts each one on the footprint as a real anchored dimension and answers MATCH or MISMATCH;+the direction (along x or y) and where the dimension line runs come from the footprint's own KiCad file. The footprint+is then shown and its frame kept (altium/footprints/<footprint>.png) with a record per part in+altium/footprint-dims.json, which the project page's design review shows. A dimension that disagrees stops the library+step (a wrong footprint is a wrong board) unless it carries "ack": "<why>".+"""++DIMS_FROM = (0, 2, 121)+CORNERS = ('TL', 'TR', 'BR', 'BL')+++def part_check_facts():+ """{MPN upper: facts} of the parts with `dims` in design/part-checks.json (beside the run, or in the working folder)."""+ for p in (Path('design/part-checks.json'), RUN.resolve().parent / 'design' / 'part-checks.json'):+ if not p.is_file(): continue+ try: d = json.loads(p.read_text())+ except Exception: continue+ facts = d.get('parts') if isinstance(d, dict) else d+ return {str(f['mpn']).upper(): f for f in facts or [] if isinstance(f, dict) and f.get('mpn') and f.get('dims')}+ return {}+++def kicad_geometry(text):+ """({pad number: (x, y)}, (x0, y0, x1, y1) of the F.Fab outline or None) of a .kicad_mod's text, its own frame."""+ pads = {}+ for m in re.finditer(r'\(pad\s+"([^"]*)"[^()]*\(at\s+([-\d.eE]+)\s+([-\d.eE]+)', text):+ pads.setdefault(m.group(1), (float(m.group(2)), float(m.group(3))))+ pts = []+ # each graphic item on its own (up to the next item), kept only when its own layer is F.Fab+ starts = [m for m in re.finditer(r'\((fp_line|fp_rect|fp_arc|fp_poly|fp_circle|fp_text|pad|property|model)\b', text)]+ for i, m in enumerate(starts):+ if m.group(1) not in ('fp_line', 'fp_rect', 'fp_arc', 'fp_poly'): continue+ seg = text[m.end():starts[i + 1].start() if i + 1 < len(starts) else len(text)]+ lay = re.search(r'\(layer\s+"([^"]+)"\)', seg)+ if not lay or lay.group(1) != 'F.Fab': continue+ pts += [(float(x), float(y)) for x, y in re.findall(r'\((?:start|end|mid|xy)\s+([-\d.eE]+)\s+([-\d.eE]+)\)', seg)]+ box = (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)) if pts else None+ return pads, box+++def _point(name, pads, box):+ if name in CORNERS:+ if not box: return None+ return {'TL': (box[0], box[1]), 'TR': (box[2], box[1]), 'BR': (box[2], box[3]), 'BL': (box[0], box[3])}[name]+ return pads.get(name)+++def verb_dims(dims, pads, box):+ """The altium_add_dimensions list for the datasheet's dims: each dimension's direction (its `axis`, else the+ longer of dx and dy) and its line outside the pads and the body, stacked when several run the same way.+ Returns (dimensions, problems)."""+ xs = [abs(p[0]) for p in pads.values()] + ([abs(box[0]), abs(box[2])] if box else [])+ ys = [abs(p[1]) for p in pads.values()] + ([abs(box[1]), abs(box[3])] if box else [])+ reach_x, reach_y = (max(xs) if xs else 1.0), (max(ys) if ys else 1.0)+ step = max(0.4, 0.15 * max(reach_x, reach_y))+ out, problems, n = [], [], {'H': 0, 'V': 0}+ for d in dims:+ a, b = str(d.get('a')), str(d.get('b'))+ pa, pb = _point(a, pads, box), _point(b, pads, box)+ if pa is None or pb is None:+ miss = a if pa is None else b+ problems.append('%s: %s' % (d.get('what') or '%s to %s' % (a, b), 'no assembly outline for the body corner ' + miss if miss in CORNERS else 'no pad ' + miss))+ continue+ axis = d.get('axis')+ dr = 'H' if axis == 'x' else 'V' if axis == 'y' else ('H' if abs(pa[0] - pb[0]) >= abs(pa[1] - pb[1]) else 'V')+ at = (reach_y if dr == 'H' else reach_x) + step * (1 + n[dr])+ # alternate sides so two dimensions the same way do not stack on one side only+ if n[dr] % 2: at = -at+ n[dr] += 1+ e = {'a': a, 'b': b, 'dir': dr, 'at': round(at, 3), 'expect': d['mm'], 'toleranceMm': d.get('tolMm', 0.05)}+ out.append(e)+ return out, problems+++def dim_format(pads, box):+ """Text and arrows scaled to the footprint: a 0603 and a QFN-48 both stay readable."""+ xs = [p[0] for p in pads.values()] + ([box[0], box[2]] if box else [])+ ys = [p[1] for p in pads.values()] + ([box[1], box[3]] if box else [])+ size = max((max(xs) - min(xs)) if xs else 1.0, (max(ys) - min(ys)) if ys else 1.0, 0.5)+ h = round(min(1.0, max(0.25, 0.18 * size)), 3)+ return {'textHeightMm': h, 'textHeight': h, 'lineWidthMm': round(h / 8, 3), 'arrowSizeMm': round(h * 0.8, 3), 'arrowLengthMm': round(h * 0.8, 3), 'extensionOffsetMm': round(h / 2, 3), 'units': 'mm'}+++def dimension_part(pcb_lib, footprint, facts, fp_text):+ """Check one imported footprint against its datasheet dims in Altium and keep its picture. Returns the record+ {footprint, mpn, source, rows, stop, acked, image}."""+ pads, box = kicad_geometry(fp_text)+ dims = [d for d in facts.get('dims') or [] if isinstance(d, dict) and d.get('mm') is not None]+ vd, problems = verb_dims(dims, pads, box)+ rec = {'footprint': footprint, 'mpn': facts.get('mpn'), 'source': facts.get('source'), 'rows': [], 'stop': ['%s: %s' % (facts.get('mpn'), p) for p in problems], 'acked': [], 'image': None}+ if not vd: return rec+ r = ab('altium_add_dimensions', {'libraryPath': win(pcb_lib), 'footprint': footprint, 'dimensions': vd, 'format': dim_format(pads, box)}, timeout=900)+ if not r.get('success'):+ rec['stop'].append('%s: altium_add_dimensions failed: %s' % (facts.get('mpn'), str(r.get('error') or r.get('errorCode'))[:200]))+ return rec+ got = r.get('dimensions') or []+ asked = [d for d in dims if _point(str(d.get('a')), pads, box) is not None and _point(str(d.get('b')), pads, box) is not None]+ for d, g in zip(asked, got):+ what = d.get('what') or '%s to %s' % (d.get('a'), d.get('b'))+ row = {'what': what, 'a': str(d.get('a')), 'b': str(d.get('b')), 'datasheetMm': d['mm'], 'footprintMm': g.get('valueMm', g.get('lengthMm')), 'check': g.get('check'), 'ack': d.get('ack')}+ rec['rows'].append(row)+ if g.get('check') != 'MATCH':+ line = '%s: %s (%s to %s) is %s mm on footprint %s, %s mm in the datasheet' % (facts.get('mpn'), what, row['a'], row['b'], row['footprintMm'], footprint, d['mm'])+ (rec['acked'] if d.get('ack') else rec['stop']).append(line + (' (acknowledged: %s)' % d['ack'] if d.get('ack') else ''))+ shot = ab('altium_show_footprint', {'libraryPath': win(pcb_lib), 'footprintName': footprint}, timeout=300).get('shot') or {}+ if isinstance(shot, dict) and shot.get('image'):+ import base64+ d = STATE / 'footprints'; d.mkdir(parents=True, exist_ok=True)+ f = d / (footprint + '.png'); f.write_bytes(base64.b64decode(shot['image'].split(',')[-1]))+ rec['image'] = str(f)+ return rec+++def save_dims_record(records):+ """altium/footprint-dims.json: the records of every footprint checked so far (a later run of the step replaces its own)."""+ f = STATE / 'footprint-dims.json'+ have = {}+ if f.is_file():+ try: have = {x['footprint']: x for x in json.loads(f.read_text())}+ except Exception: have = {}+ for x in records: have[x['footprint']] = x+ f.write_text(json.dumps(list(have.values()), indent=1))+ return f
tools/altium-project.py+31−1@@ -154,6 +154,10 @@ def cmd_library(a): refs[c.get('ref')] = key only = {fp_name(m) for m in (a.only or [])} if only - set(work): err('--only names part(s) not in --parts: %s' % ', '.join(sorted(only - set(work))))+ # #43: the datasheet's dimensions (design/part-checks.json `dims`), checked in Altium on each imported footprint+ pc_facts = part_check_facts() if version_tuple(ver) >= DIMS_FROM else {}+ dim_recs, dim_skipped = [], []+ prev_parts = json.loads(json.dumps(st.get('parts') or {})) for key, w in work.items(): if w['origin'] == 'project-lib': from_lib.append(w['mpn']) if only and key not in only:@@ -164,9 +168,11 @@ def cmd_library(a): if w['origin'] == 'board-only': files, spec_sym = convert_part(key, key, {'fp': w['footprint'], 'desc': 'board-only pad'}, stage) step = None+ fp_path = w['footprint'] else: src = part_source(key, w) files, spec_sym = convert_part(key, w['mpn'], src, stage)+ fp_path = src['fp'] step = src.get('step') numbers, notes = lookup_numbers(w['mpn'], src.get('links'), cache) mfr = src.get('mfr') or ''@@ -192,6 +198,17 @@ def cmd_library(a): se = spice_entry(w) if spec_sym and w['origin'] != 'board-only' else None if se: st['parts'][key]['sim'] = attach_spice(key, se, sch_lib, bdir) if w['origin'] == 'project-lib': st['parts'][key]['projectLib'] = {'dir': w['projectLib'].get('dir'), 'source': w['projectLib'].get('source')}+ facts = pc_facts.get(str(w.get('mpn') or '').upper())+ # a footprint dimensioned by an earlier run keeps those dimensions through a re-import, and the bridge adds to+ # what is there: dimension it once, so a rerun does not stack copies+ prev_dims = (prev_parts.get(key) or {}).get('dims')+ if facts and prev_dims and prev_dims.get('rows'):+ st['parts'][key]['dims'] = prev_dims+ dim_skipped.append(key)+ elif facts:+ rec = dimension_part(pcb_lib, key, facts, Path(fp_path).read_text(errors='ignore'))+ dim_recs.append(rec)+ st['parts'][key]['dims'] = {'rows': rec['rows'], 'image': rec['image'], 'stop': rec['stop']} added.append(key) say('part %s: footprint%s%s%s, refs %s%s' % (key, ', symbol' if spec_sym else '', ', 3D' if step else '', (', SPICE model' if st['parts'][key].get('sim', {}).get('attached') else ', no SPICE model (%s)' % st['parts'][key]['sim'].get('why')) if st['parts'][key].get('sim') else '', ' '.join(r for r in w['refs'] if r) or '-', ' (from the project library)' if w['origin'] == 'project-lib' else '')) save_state(st)@@ -205,13 +222,26 @@ def cmd_library(a): if row.get('footprint') in st['parts']: st['parts'][row['footprint']]['silk'] = row silk_notes = silk_lines(rows, smin) save_state(st)+ dim_notes = []+ if dim_skipped:+ dim_notes.append('already dimensioned in Altium by an earlier run, not dimensioned again (the bridge would add copies): %s; `part-check` measures them again from the footprint files' % ', '.join(dim_skipped))+ if dim_recs:+ dfile = save_dims_record(dim_recs)+ stops = [s for x in dim_recs for s in x['stop']]+ acked = [s for x in dim_recs for s in x['acked']]+ if stops:+ err('a footprint disagrees with its datasheet\'s dimensions (a wrong footprint is a wrong board):\n ' + '\n '.join(stops),+ ['The library is built; the dimensioned footprints are pictured in %s. Check the drawing again: fix the footprint (its page when it is yours, or open an issue on it) or give the part from the project library with "prefer": true, then `altium library --again`; a difference that is fine takes "ack": "<why>" on that dimension in design/part-checks.json.' % (STATE / 'footprints')])+ n = sum(len(x['rows']) for x in dim_recs)+ dim_notes.append('%d footprint(s) checked against their datasheets in Altium: %d dimension(s) match%s; pictures in %s (the project page shows them)'+ % (len(dim_recs), n - len(acked), (', %d acknowledged: %s' % (len(acked), '; '.join(acked))) if acked else '', STATE / 'footprints')) prove('library', {'name': name, 'parts': len(st['parts']), 'tool': 'altium', 'projectLibParts': from_lib, 'spiceModels': sum(1 for p in st['parts'].values() if (p.get('sim') or {}).get('attached'))}) if fix and fix.get('repaired'): say('repaired %s: %d layer records (mechanical up to %d) became %d (up to %d), %d footprint(s) copied; the old file is kept as %s' % (pcb_lib, fix['records'], fix['highestMechanical'], fix['after']['records'], fix['after']['highestMechanical'], fix['footprints'], fix['kept'])) ok('library %s: %d part(s) (%d added, %d kept%s): %s and %s' % (name, len(st['parts']), len(added), len(kept), '; %d from the board\'s project library: %s' % (len(from_lib), ', '.join(from_lib)) if from_lib else '', pcb_lib, sch_lib),- silk_notes + spice_summary(st['parts']) + ['No distributor number yet: ' + '; '.join('%s %s' % (m, ' '.join(v)) for m, v in unverified.items()) + '. Run `altium library` again when the services are back, or add the numbers to the part\'s wiki page (a project-library part: "mouser"/"digikey"/"lcsc" in its provenance.json entry).' if unverified else '',+ dim_notes + silk_notes + spice_summary(st['parts']) + ['No distributor number yet: ' + '; '.join('%s %s' % (m, ' '.join(v)) for m, v in unverified.items()) + '. Run `altium library` again when the services are back, or add the numbers to the part\'s wiki page (a project-library part: "mouser"/"digikey"/"lcsc" in its provenance.json entry).' if unverified else '', 'Next: adom-aiflow altium reference --kicad <reference .kicad_pcb> --spec <spec.json> (if there is a reference board), then adom-aiflow altium schematic --netlist <netlist.json> --name <Design> (the schematic, then the board in the same project).'])