← All Pull Requests
adom-aiflow-jlcpcb 0.1.6: the rotation check names how each part was matched #4
Merges
jlcpcb-0.1.6 → mainadom-aiflow-jlcpcb 0.1.6: the rotation check names how each part was matched. Closes #3.
- Every pad is kept on both sides (repeated numbers too; the old maps kept one pad per number).
- Each part is classified, with no tolerance change:
pad-numbers,repeated-pads-as-set,explicit-pin-map(overrides{"pins": {...}, "deg": n}),geometry-pin-map(only when one rotation fits, or the numbers decide),alternate-land(same arrangement at another size: a review note with the rotation, never a pass),unexplained(a failure for the drawing review; a symmetric part the numbers cannot orient lands here). - The record carries
case,caseNote,pinMapandpinMapFrom; the skill lists the cases.
Tests: 13 (new: repeated pads as a set, geometry and explicit pin maps, the symmetric case that stays unexplained, alternate land vs a different package vs plain numbers). Not checked against the electronic-load board's eleven parts (their vendor responses are not here).
🤖 Generated with Claude Code
Diff Skip to comments
Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-aiflow-jlcpcb"-version = "0.1.5"+version = "0.1.6" dependencies = [ "clap", "regex",
Cargo.toml+1−1@@ -2,7 +2,7 @@ # Copied from adom/adom-aiflow template/flow-app. This copy is yours: change anything, never depend on aiflow. [package] name = "adom-aiflow-jlcpcb"-version = "0.1.5"+version = "0.1.6" edition = "2021" license = "MIT"
bin/adom-aiflow-jlcpcb⋯ 1 unchanged line ⋯
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow-jlcpcb", "type": "app",- "version": "0.1.5",+ "version": "0.1.6", "title": "AI Flow: JLCPCB", "description": "The JLCPCB ordering stage of AI Flow: from a finished board to assembled boards from JLCPCB. Part substitutes proven from both datasheets, the gerber zip, BOM and CPL from the desktop's own KiCad, every part's rotation checked against JLCPCB's own footprint and corrected, placement-preview evidence, the quote, the human's recorded OK before payment, and rotation corrections shared on component pages. Open source (MIT): build it with ./build.sh.", "category": "Developer Tools",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow-jlcpcb", "type": "app",- "version": "0.1.5",+ "version": "0.1.6", "title": "AI Flow: JLCPCB", "description": "The JLCPCB ordering stage of AI Flow: from a finished board to assembled boards from JLCPCB. Part substitutes proven from both datasheets, the gerber zip, BOM and CPL from the desktop's own KiCad, every part's rotation checked against JLCPCB's own footprint and corrected, placement-preview evidence, the quote, the human's recorded OK before payment, and rotation corrections shared on component pages. Open source (MIT): build it with ./build.sh.", "category": "Developer Tools",
skills/adom-aiflow-jlcpcb/SKILL.md+8@@ -85,6 +85,14 @@ Default checks preserve the original ratings. A lower rating requires a document Keep quote alternatives in a separate BOM/run. Do not rewrite the released design or imply the quoted variant is manufacturing-qualified. Record the vendor's actual PCB, assembly, parts, attrition, shipping and tax breakdown; never feed a catalog subtotal into `quote` as if it came from checkout. Purchase still requires the user's approval. +Each part's rotation record says how its two footprints were matched (`case`, issue #3); the tolerance is never relaxed:+- `pad-numbers`: pad for pad, every pad within the tolerance.+- `repeated-pads-as-set`: pads sharing a number (a split thermal pad, mounting tabs) matched as a set.+- `explicit-pin-map`: the KiCad pads renumbered by a pin map you give in the overrides, `{"<ref or KiCad footprint>": {"pins": {"<KiCad pad>": "<JLCPCB pad>"}, "deg": <optional hand-set degrees>}}`, for a connector whose shield or mechanical pads EasyEDA numbers its own way.+- `geometry-pin-map`: the numbers differ, but the pad geometry lands at exactly one rotation (or the numbers decide between the ones that fit); the implied map is recorded as `pinMap`.+- `alternate-land`: the same pad arrangement at another size (another pitch or pad size): a dimensionally different land, not a rotation error. The rotation is taken from the arrangement and the part stays flagged for review against the manufacturer's drawing (a note, not a pass).+- `unexplained`: none of the above (a symmetric part the numbers cannot orient, a different package, a missing pad). It stays a failure for the manufacturer-drawing review; give it a pin map when the drawing settles it.+ Vendor 403/access errors are `retrieval-unverified`, not evidence of a missing footprint. Report those parts as not verified (they stay flagged for the preview). Do not use a manual/no-footprint override to bypass a network problem. Resume after access works; verify the vendor placement preview before recording a complete quote. ## Continue to the user's requested finish line
src/kicad.rs+8−3@@ -8,7 +8,9 @@ pub struct Pad { pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub rot: f64 } #[derive(Clone, Debug)] #[allow(dead_code)] // placement fields kept for stages that need them-pub struct Footprint { pub reference: String, pub name: String, pub x: f64, pub y: f64, pub rot: f64, pub bottom: bool, pub pads: BTreeMap<String, Pad> }+pub struct Footprint { pub reference: String, pub name: String, pub x: f64, pub y: f64, pub rot: f64, pub bottom: bool, pub pads: BTreeMap<String, Pad>,+ /// every pad, a repeated number (a split thermal pad, a mounting tab) included (issue #3)+ pub all_pads: Vec<(String, Pad)> } /// Each top-level `(footprint ...)` block, matching parentheses outside quoted strings. fn blocks(t: &str) -> Vec<&str> {@@ -45,10 +47,13 @@ pub fn footprints(text: &str) -> BTreeMap<String, Footprint> { let (x, y, rot) = re_at.captures(b).map(|c| (f(&c[1]), f(&c[2]), c.get(3).map(|m| f(m.as_str())).unwrap_or(0.0))).unwrap_or((0.0, 0.0, 0.0)); let head = &b[..b.len().min(400)]; let mut pads = BTreeMap::new();+ let mut all_pads = Vec::new(); for c in re_pad.captures_iter(b) {- pads.entry(c[1].to_string()).or_insert(Pad { x: f(&c[2]), y: f(&c[3]), rot: c.get(4).map(|m| f(m.as_str())).unwrap_or(0.0), w: f(&c[5]), h: f(&c[6]) });+ let pad = Pad { x: f(&c[2]), y: f(&c[3]), rot: c.get(4).map(|m| f(m.as_str())).unwrap_or(0.0), w: f(&c[5]), h: f(&c[6]) };+ all_pads.push((c[1].to_string(), pad.clone()));+ pads.entry(c[1].to_string()).or_insert(pad); }- out.insert(reference.clone(), Footprint { reference, name, x, y, rot, bottom: head.contains("(layer \"B.Cu\")"), pads });+ out.insert(reference.clone(), Footprint { reference, name, x, y, rot, bottom: head.contains("(layer \"B.Cu\")"), pads, all_pads }); } out }
src/rotation.rs+206−13@@ -25,7 +25,8 @@ pub const PAGE_FILE: &str = "jlcpcb-rotation.json"; type Pads = BTreeMap<String, (f64, f64)>; -pub struct JlcFootprint { pub title: String, pub pads: Pads }+/// `all`: every vendor pad, repeated numbers included (issue #3).+pub struct JlcFootprint { pub title: String, pub pads: Pads, pub all: Vec<(String, (f64, f64))> } /// JLCPCB's footprint for one LCSC number, or None when EasyEDA has none. pub fn jlc_footprint(br: &Bridge, lcsc: &str, native: Option<(&str,&str)>, evidence: &Path) -> Result<Option<JlcFootprint>, String> {@@ -79,14 +80,17 @@ await new Promise(r=>setTimeout(r,500))}}return JSON.stringify({{error:location. let num = |v: &Value| v.as_str().and_then(|s| s.parse::<f64>().ok()).or_else(|| v.as_f64()).unwrap_or(0.0); let (hx, hy) = (num(&head["x"]), num(&head["y"])); let mut pads = Pads::new();+ let mut all = Vec::new(); for s in d["pads"].as_array().into_iter().flatten().filter_map(|s| s.as_str()) { let f: Vec<&str> = s.split('~').collect(); // PAD~shape~x~y~w~h~layer~net~number~... if f.len() < 9 { continue; } if let (Ok(x), Ok(y)) = (f[2].parse::<f64>(), f[3].parse::<f64>()) {- pads.entry(f[8].to_string()).or_insert(((x - hx) * MIL, (y - hy) * MIL));+ let at = ((x - hx) * MIL, (y - hy) * MIL);+ all.push((f[8].to_string(), at));+ pads.entry(f[8].to_string()).or_insert(at); } }- Ok(Some(JlcFootprint { title: d["title"].as_str().unwrap_or("").to_string(), pads }))+ Ok(Some(JlcFootprint { title: d["title"].as_str().unwrap_or("").to_string(), pads, all })) } /// Parse only successful vendor data; access errors never count as absent geometry.@@ -101,13 +105,16 @@ fn parse_vendor(d:&Value)->Result<Option<JlcFootprint>,String> { let num=|v:&Value|v.as_f64().or_else(||v.as_str().and_then(|s|s.parse::<f64>().ok())); let (hx,hy)=(num(&head["x"]).ok_or("missing origin x")?,num(&head["y"]).ok_or("missing origin y")?); let mut pads=Pads::new();+ let mut all=Vec::new(); for s in ds["shape"].as_array().into_iter().flatten().filter_map(|v|v.as_str()).filter(|s|s.starts_with("PAD~")) { let f:Vec<_>=s.split('~').collect();if f.len()<9 {return Err("malformed vendor pad".into());} let x:f64=f[2].parse().map_err(|_|"invalid pad x")?;let y:f64=f[3].parse().map_err(|_|"invalid pad y")?;- pads.entry(f[8].to_string()).or_insert(((x-hx)*MIL,(y-hy)*MIL));+ let at=((x-hx)*MIL,(y-hy)*MIL);+ all.push((f[8].to_string(),at));+ pads.entry(f[8].to_string()).or_insert(at); } if pads.len()<2{return Err("vendor footprint has fewer than two numbered pads".into());}- Ok(Some(JlcFootprint{title:p["title"].as_str().unwrap_or("").into(),pads}))+ Ok(Some(JlcFootprint{title:p["title"].as_str().unwrap_or("").into(),pads,all})) } /// Rotate CCW-positive (as seen y-up) in y-down coordinates.@@ -133,6 +140,134 @@ pub fn fit(e: &Pads, k: &Pads) -> Option<Fit> { best } +type All = Vec<(String, (f64, f64))>;++/// How a part's two footprints were matched (issue #3). The tolerance is never relaxed: every case but+/// `AlternateLand` needs each pad within it; `AlternateLand` is a review item, never a pass.+#[derive(Debug, Clone, PartialEq)]+pub enum Case { Numbers, RepeatedAsSet, ExplicitPinMap, GeometryPinMap, AlternateLand, Unexplained }++impl Case {+ pub fn name(&self) -> &'static str {+ match self { Case::Numbers => "pad-numbers", Case::RepeatedAsSet => "repeated-pads-as-set", Case::ExplicitPinMap => "explicit-pin-map",+ Case::GeometryPinMap => "geometry-pin-map", Case::AlternateLand => "alternate-land", Case::Unexplained => "unexplained" }+ }+}++pub struct Classified { pub case: Case, pub fit: Fit, pub mapping: Option<BTreeMap<String, String>>, pub note: String }++fn centroid(p: &[(f64, f64)]) -> (f64, f64) { let n = p.len().max(1) as f64; (p.iter().map(|q| q.0).sum::<f64>() / n, p.iter().map(|q| q.1).sum::<f64>() / n) }+fn dist(a: (f64, f64), b: (f64, f64)) -> f64 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() }++/// Greedy nearest one-to-one assignment of `a` onto `b`: the largest of the paired distances.+fn set_error(a: &[(f64, f64)], b: &[(f64, f64)]) -> f64 {+ let mut pairs: Vec<(f64, usize, usize)> = a.iter().enumerate().flat_map(|(i, p)| b.iter().enumerate().map(move |(j, q)| (dist(*p, *q), i, j))).collect();+ pairs.sort_by(|x, y| x.0.total_cmp(&y.0));+ let (mut ua, mut ub, mut worst, mut n) = (vec![false; a.len()], vec![false; b.len()], 0.0f64, 0);+ for (d, i, j) in pairs { if !ua[i] && !ub[j] { ua[i] = true; ub[j] = true; worst = worst.max(d); n += 1; } }+ if n < a.len().min(b.len()) { f64::INFINITY } else { worst }+}++/// Pad number for pad number, repeated numbers matched as a set: the best of the four rotations.+fn fit_by_numbers(e: &All, k: &All) -> Option<(Fit, bool)> {+ let group = |v: &All| { let mut m: BTreeMap<String, Vec<(f64, f64)>> = BTreeMap::new(); for (n, p) in v { if !n.is_empty() { m.entry(n.clone()).or_default().push(*p); } } m };+ let (ge, gk) = (group(e), group(k));+ let common: Vec<&String> = gk.keys().filter(|n| ge.contains_key(*n)).collect();+ let pads: usize = common.iter().map(|n| gk[*n].len().min(ge[*n].len())).sum();+ if pads < 2 { return None; }+ let repeated = common.iter().any(|n| gk[*n].len() > 1 || ge[*n].len() > 1);+ let mut best: Option<Fit> = None;+ for d in [0i64, 90, 180, 270] {+ let re: BTreeMap<&String, Vec<(f64, f64)>> = common.iter().map(|n| (*n, ge[*n].iter().map(|p| rot(*p, d as f64)).collect())).collect();+ // the offset from the centroids of every common pad (a repeated set's centroid is its own)+ let ce = centroid(&common.iter().flat_map(|n| re[*n].iter().copied()).collect::<Vec<_>>());+ let ck = centroid(&common.iter().flat_map(|n| gk[*n].iter().copied()).collect::<Vec<_>>());+ let t = (ck.0 - ce.0, ck.1 - ce.1);+ let err = common.iter().map(|n| { let moved: Vec<(f64, f64)> = re[*n].iter().map(|p| (p.0 + t.0, p.1 + t.1)).collect(); set_error(&moved, &gk[*n]) }).fold(0.0, f64::max);+ if best.as_ref().map(|b| err < b.residual).unwrap_or(true) { best = Some(Fit { delta: d, residual: err, offset: t, compared: pads }); }+ }+ best.map(|b| (b, repeated))+}++/// Ignore the numbers: the rotations at which the two pad sets land on each other, with the K->E numbering each implies.+fn fits_by_geometry(e: &All, k: &All, tol: f64) -> Vec<(Fit, BTreeMap<String, String>)> {+ if e.len() != k.len() || e.len() < 2 { return Vec::new(); }+ let mut out = Vec::new();+ for d in [0i64, 90, 180, 270] {+ let re: Vec<(f64, f64)> = e.iter().map(|(_, p)| rot(*p, d as f64)).collect();+ let (ce, ck) = (centroid(&re), centroid(&k.iter().map(|(_, p)| *p).collect::<Vec<_>>()));+ let t = (ck.0 - ce.0, ck.1 - ce.1);+ let mut used = vec![false; e.len()];+ let (mut worst, mut map) = (0.0f64, BTreeMap::new());+ for (kn, kp) in k {+ let Some((j, dd)) = re.iter().enumerate().filter(|(j, _)| !used[*j]).map(|(j, p)| (j, dist((p.0 + t.0, p.1 + t.1), *kp))).min_by(|a, b| a.1.total_cmp(&b.1)) else { worst = f64::INFINITY; break };+ used[j] = true; worst = worst.max(dd); map.insert(kn.clone(), e[j].0.clone());+ }+ if worst <= tol { out.push((Fit { delta: d, residual: worst, offset: t, compared: k.len() }, map)); }+ }+ out+}++/// Same arrangement at another size (a manufacturer's alternative land, a different pitch): numbers kept, both sides+/// centred and scaled to unit spread. Returns the rotation and the normalised error.+fn fit_shape(e: &All, k: &All) -> Option<(i64, f64, (f64, f64))> {+ let common: Vec<(&(f64, f64), &(f64, f64))> = k.iter().filter_map(|(n, kp)| e.iter().find(|(m, _)| m == n).map(|(_, ep)| (ep, kp))).collect();+ if common.len() < 3 { return None; }+ let norm = |v: &[(f64, f64)]| { let c = centroid(v); let s = (v.iter().map(|p| dist(*p, c).powi(2)).sum::<f64>() / v.len() as f64).sqrt().max(1e-9); (c, s) };+ let kp: Vec<(f64, f64)> = common.iter().map(|x| *x.1).collect();+ let (ck, sk) = norm(&kp);+ let mut best: Option<(i64, f64, (f64, f64))> = None;+ for d in [0i64, 90, 180, 270] {+ let ep: Vec<(f64, f64)> = common.iter().map(|x| rot(*x.0, d as f64)).collect();+ let (ce, se) = norm(&ep);+ let err = ep.iter().zip(&kp).map(|(a, b)| dist(((a.0 - ce.0) / se, (a.1 - ce.1) / se), ((b.0 - ck.0) / sk, (b.1 - ck.1) / sk))).fold(0.0, f64::max);+ if best.map(|b| err < b.1).unwrap_or(true) { best = Some((d, err, (ck.0 - ce.0, ck.1 - ce.1))); }+ }+ best+}++/// The normalised error under which two pad sets are the same arrangement (shape, not position).+const SHAPE_TOL: f64 = 0.12;++/// Classify one part (issue #3): by numbers (repeated pads as a set), by an explicit pin map, by geometry when+/// only one rotation fits, as an alternate land, or unexplained. `pin_map` maps KiCad pad numbers to JLCPCB's.+pub fn classify(e: &All, k: &All, tol: f64, pin_map: Option<&BTreeMap<String, String>>) -> Option<Classified> {+ let by_num = fit_by_numbers(e, k);+ if let Some((f, rep)) = &by_num {+ if f.residual <= tol { return Some(Classified { case: if *rep { Case::RepeatedAsSet } else { Case::Numbers }, fit: Fit { ..*f }, mapping: None, note: if *rep { "repeated pad numbers matched as a set".into() } else { String::new() } }); }+ }+ if let Some(m) = pin_map {+ let k2: All = k.iter().map(|(n, p)| (m.get(n).cloned().unwrap_or_else(|| n.clone()), *p)).collect();+ if let Some((f, _)) = fit_by_numbers(e, &k2).filter(|(f, _)| f.residual <= tol) {+ return Some(Classified { case: Case::ExplicitPinMap, fit: f, mapping: Some(m.clone()), note: "KiCad pads renumbered by the part's pin map".into() });+ }+ }+ let geo = fits_by_geometry(e, k, tol);+ match geo.len() {+ 1 => { let (f, map) = geo.into_iter().next().unwrap(); return Some(Classified { case: Case::GeometryPinMap, fit: f, mapping: Some(map), note: "vendor and KiCad pad numbers differ; matched by pad geometry, one rotation fits".into() }); }+ n if n > 1 => {+ // symmetric: the numbers decide between the rotations that fit; the most identical numbers wins when unique+ let agree = |m: &BTreeMap<String, String>| m.iter().filter(|(a, b)| a == b).count();+ let top = geo.iter().map(|g| agree(&g.1)).max().unwrap_or(0);+ let winners: Vec<&(Fit, BTreeMap<String, String>)> = geo.iter().filter(|g| agree(&g.1) == top).collect();+ if winners.len() == 1 && top >= 1 {+ let (f, map) = winners[0];+ return Some(Classified { case: Case::GeometryPinMap, fit: Fit { ..*f }, mapping: Some(map.clone()), note: format!("matched by pad geometry; of the {n} rotations that fit, the pad numbers agree best at this one") });+ }+ let ds: Vec<String> = geo.iter().map(|g| format!("{:+}", signed(g.0.delta))).collect();+ let (f, _) = &geo[0];+ return Some(Classified { case: Case::Unexplained, fit: Fit { ..*f }, mapping: None, note: format!("the pad geometry fits at {} and the pad numbers do not decide: give the part a pin map, or check pin 1 in the manufacturer's drawing", ds.join(" and ")) });+ }+ _ => {}+ }+ if let Some((d, err, t)) = fit_shape(e, k).filter(|x| x.1 <= SHAPE_TOL) {+ let res = by_num.as_ref().map(|b| b.0.residual).unwrap_or(f64::INFINITY);+ return Some(Classified { case: Case::AlternateLand, fit: Fit { delta: d, residual: res, offset: t, compared: k.len().min(e.len()) }, mapping: None,+ note: format!("the same pad arrangement at another size (normalised error {err:.3}): a dimensionally different land, not a rotation error; check the land against the manufacturer's drawing") });+ }+ by_num.map(|(f, _)| Classified { case: Case::Unexplained, fit: f, mapping: None, note: "no case explains the difference: footprint identity, a missing or extra pad, or a different package".into() })+}+ fn r4(v: f64) -> f64 { (v * 10000.0).round() / 10000.0 } pub fn signed(delta: i64) -> i64 { (delta + 180).rem_euclid(360) - 180 } @@ -170,7 +305,7 @@ pub fn check(br: &Bridge, board: &Path, bom: &Table, overrides: &Map<String, Val } let mut by_fp: BTreeMap<String, String> = BTreeMap::new(); // KiCad footprint -> an LCSC number with a JLCPCB footprint for rf in &order { if cache[&lcsc[rf]].is_some() { by_fp.entry(parts[rf].name.clone()).or_insert(lcsc[rf].clone()); } }- let ov = |rf: &str, fp: &str| overrides.get(rf).or_else(|| overrides.get(fp)).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)));+ let ov = |rf: &str, fp: &str| overrides.get(rf).or_else(|| overrides.get(fp)).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)).or_else(|| v["deg"].as_i64())); let (mut recs, mut failed, mut warned) = (Vec::new(), Vec::new(), Vec::new()); for rf in &order { let (c, p) = (&lcsc[rf], &parts[rf]);@@ -192,26 +327,34 @@ pub fn check(br: &Bridge, board: &Path, bom: &Table, overrides: &Map<String, Val } recs.push(rec); continue; };- let k: Pads = p.pads.iter().map(|(n, q)| (n.clone(), (q.x, q.y))).collect(); let mut rec = base; rec["jlcFootprint"] = json!(jf.title); if src != *c { rec["jlcFootprintFrom"] = json!(src); }- let Some(f) = fit(&jf.pads, &k) else {- failed.push((rf.clone(), format!("no common pad numbers between {} and {}", p.name, jf.title)));- rec["status"] = json!("no-match"); recs.push(rec); continue;+ // issue #3: every pad, repeated numbers too; an explicit pin map from the overrides ({"pins": {kicad: jlc}})+ let k_all: All = p.all_pads.iter().map(|(n, q)| (n.clone(), (q.x, q.y))).collect();+ let e_all: All = if jf.all.is_empty() { jf.pads.iter().map(|(n, q)| (n.clone(), *q)).collect() } else { jf.all.clone() };+ let pin_map: Option<BTreeMap<String, String>> = overrides.get(rf.as_str()).or_else(|| overrides.get(&p.name)).and_then(|v| v["pins"].as_object()).map(|o| o.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect());+ let Some(cl) = classify(&e_all, &k_all, tol, pin_map.as_ref()) else {+ failed.push((rf.clone(), format!("no common pad numbers between {} and {}, and the pad geometry does not match either", p.name, jf.title)));+ rec["status"] = json!("no-match"); rec["case"] = json!("unexplained"); recs.push(rec); continue; };+ rec["case"] = json!(cl.case.name());+ if !cl.note.is_empty() { rec["caseNote"] = json!(cl.note); }+ if let Some(m) = &cl.mapping { rec["pinMap"] = json!(m); rec["pinMapFrom"] = json!(if cl.case == Case::ExplicitPinMap { "overrides" } else { "pad geometry" }); }+ let f = cl.fit; rec["delta"] = json!(f.delta); rec["residual_mm"] = json!(r4(f.residual)); rec["offset_mm"] = json!([r4(f.offset.0), r4(f.offset.1)]); rec["pads_compared"] = json!(f.compared); rec["jlcRotation"] = json!((p.rot + f.delta as f64).rem_euclid(360.0)); let (ox, oy) = rot((r4(f.offset.0), r4(f.offset.1)), p.rot); // into the board frame (y down) rec["centroidShiftBoard_mm"] = json!([r4(-ox), r4(-oy)]);- let ok = r4(f.residual) <= tol;- rec["status"] = json!(if ok { "ok" } else { "mismatch" });+ let ok = r4(f.residual) <= tol && !matches!(cl.case, Case::AlternateLand | Case::Unexplained);+ rec["status"] = json!(if ok { "ok" } else if cl.case == Case::AlternateLand { "alternate-land" } else { "mismatch" }); rec["pads"] = json!({"kicad": p.pads.iter().map(|(n, q)| (n.clone(), json!([r4(q.x), r4(q.y), r4(q.w), r4(q.h)]))).collect::<Map<_, _>>(), "jlc": jf.pads.iter().map(|(n, q)| (n.clone(), json!([r4(q.0), r4(q.1)]))).collect::<Map<_, _>>()}); if let Some(m) = ov(rf, &p.name) { if ok && m.rem_euclid(360) != f.delta { warned.push((rf.clone(), format!("hand-set correction {m:+} disagrees with the pad fit ({:+}); the pad fit wins", signed(f.delta)))); } }- if !ok { failed.push((rf.clone(), format!("best rotation leaves {:.3} mm error (> {tol:.2}): review terminal numbering, repeated pads, land dimensions, footprint identity and orientation", f.residual))); }+ if cl.case == Case::AlternateLand { warned.push((rf.clone(), format!("{} (rotation {:+} from the pad arrangement)", cl.note, signed(f.delta)))); }+ else if !ok { failed.push((rf.clone(), format!("{} (best rotation leaves {:.3} mm error, tolerance {tol:.2}): review it against the manufacturer's drawing", cl.note, f.residual))); } recs.push(rec); } let record = json!({"schema": "adom/jlcpcb-rotation-run@1", "board": board.canonicalize().unwrap_or(board.to_path_buf()).display().to_string(),@@ -348,6 +491,56 @@ mod tests { assert!(parse_vendor(&json!({"success":true,"result":{"packageDetail":{"dataStr":{}}}})).is_err()); } + fn all(v: &[(&str, (f64, f64))]) -> All { v.iter().map(|(n, p)| (n.to_string(), *p)).collect() }+ fn turned(v: &All, d: f64, t: (f64, f64)) -> All { v.iter().map(|(n, p)| { let r = rot(*p, d); (n.clone(), (r.0 + t.0, r.1 + t.1)) }).collect() }+ const SOT: [(&str, (f64, f64)); 3] = [("1", (-0.95, 1.1)), ("2", (0.95, 1.1)), ("3", (0.0, -1.1))];++ /// Issue #3: every case is named, and the tolerance is never relaxed.+ #[test]+ fn repeated_pads_match_as_a_set() {+ // a QFN-ish part: pins 1..4 and an exposed pad split into four, all numbered 5, listed in another order+ let e = all(&[("1", (-2.0, -1.0)), ("2", (-2.0, 1.0)), ("3", (2.0, 1.0)), ("4", (2.0, -1.0)), ("5", (-0.5, -0.5)), ("5", (0.5, -0.5)), ("5", (-0.5, 0.5)), ("5", (0.5, 0.5))]);+ let mut k = turned(&e, 90.0, (0.2, 0.0));+ k.swap(4, 7);+ let c = classify(&e, &k, 0.05, None).unwrap();+ assert_eq!((c.case, c.fit.delta), (Case::RepeatedAsSet, 90));+ // the old map kept one pad 5 of four and could not tell+ assert!(c.fit.residual < 1e-9);+ }++ #[test]+ fn different_numbering_is_matched_by_geometry_or_an_explicit_map() {+ let e = all(&SOT);+ // the same land, KiCad numbering its pads A, B, C+ let k: All = turned(&e, 180.0, (0.0, 0.0)).into_iter().map(|(n, p)| (match n.as_str() { "1" => "A", "2" => "B", _ => "C" }.to_string(), p)).collect();+ let c = classify(&e, &k, 0.05, None).unwrap();+ assert_eq!(c.case, Case::GeometryPinMap);+ assert_eq!(c.mapping.unwrap()["A"], "1");+ // two pads only (symmetric): geometry fits at two rotations and the numbers cannot decide+ let e2 = all(&[("1", (-0.5, 0.0)), ("2", (0.5, 0.0))]);+ let k2: All = turned(&e2, 0.0, (0.0, 0.0)).into_iter().map(|(n, p)| (if n == "1" { "+" } else { "-" }.to_string(), p)).collect();+ let c2 = classify(&e2, &k2, 0.05, None).unwrap();+ assert_eq!(c2.case, Case::Unexplained, "{}", c2.note);+ let map: BTreeMap<String, String> = [("+".to_string(), "1".to_string()), ("-".to_string(), "2".to_string())].into();+ let c3 = classify(&e2, &k2, 0.05, Some(&map)).unwrap();+ assert_eq!((c3.case, c3.fit.delta), (Case::ExplicitPinMap, 0));+ }++ #[test]+ fn a_land_at_another_size_is_an_alternate_land_not_a_pass() {+ let e = all(&[("1", (-1.27, -1.0)), ("2", (0.0, -1.0)), ("3", (1.27, -1.0)), ("4", (1.27, 1.0)), ("5", (0.0, 1.0)), ("6", (-1.27, 1.0))]);+ // KiCad's land: the same six pads at 1.3 pitch and 2.2 row spacing, turned 270+ let k = turned(&all(&[("1", (-1.3, -1.1)), ("2", (0.0, -1.1)), ("3", (1.3, -1.1)), ("4", (1.3, 1.1)), ("5", (0.0, 1.1)), ("6", (-1.3, 1.1))]), 270.0, (0.0, 0.0));+ let c = classify(&e, &k, 0.05, None).unwrap();+ assert_eq!((c.case, c.fit.delta), (Case::AlternateLand, 270));+ // a different package altogether stays unexplained+ let k2 = all(&[("1", (-3.0, 0.0)), ("2", (0.0, 2.0)), ("3", (3.0, 0.0)), ("4", (0.0, -2.0)), ("5", (1.0, 1.0)), ("6", (-0.2, 0.3))]);+ assert_eq!(classify(&e, &k2, 0.05, None).unwrap().case, Case::Unexplained);+ // and the plain case is still plain+ let k3 = turned(&e, 90.0, (0.1, -0.1));+ assert_eq!(classify(&e, &k3, 0.05, None).unwrap().case, Case::Numbers);+ }+ #[test] fn finds_a_quarter_turn() { // a SOT-23-6 style footprint, turned 90 degrees and shifted on the board side
Comments
Log in to comment.
No comments yet.