by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
← Commit history
0.2.88: export_3d, edit_pours, import_step, tool_update, import_design (kicad); engine 0.24.0 (bom, cross_check); pour ids
21 files changed
+1121−263
CHANGELOG.md+21README.md+9−4bridge-rs/Cargo.lock+1−1bridge-rs/src/bom.rs+57−243bridge-rs/src/editpours.rs+138bridge-rs/src/geom3d.rs+234bridge-rs/src/importdesign.rs+30bridge-rs/src/main.rs+5−1bridge-rs/src/routing.rs+6−1bridge-rs/src/toolupdate.rs+72bridge-rs/src/verbs.rs+62−3bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1bridge-rs/vendor/adom-eda-checks/README.md+2bridge-rs/vendor/adom-eda-checks/src/bom.rs+294bridge-rs/vendor/adom-eda-checks/src/lib.rs+4−1dev-skills/altium-bridge-test/run_verb_tests.py+19−1package.json+8−2page.json+8−2src/BRIDGE_VERSION+1−1src/agent/AdomAgent.pas.tmpl+142src/bridge.json+7−2CHANGELOG.md+21@@ -1,5 +1,26 @@ # Changelog +## 0.2.88++- **`altium_import_step`** (EDA Bridge Standard #29, native): a STEP placed with the board as free 3D geometry (an enclosure, a bracket, a lid) for fit checks. It is a 3D body of the board itself, on a mechanical layer, belonging to no part (`add_body` puts a model on one footprint).+ - Placement: at `at` (its own origin, in the board model's frame), turned by `rotation`, raised by `standoffMm`, on the top or bottom.+ - The answer gives its plan box and height and `meets`: the parts' bodies it overlaps in plan and height, from the same boxes `height_check` reads.+- **`altium_edit_pours`** (#29, native): change existing pours in place, by `pour_state`'s `id` (the standard's pour handle), by name, or by net and layer: net, layer, hatching, minimum width, grid, dead copper, islands, necks, pouring over same-net objects, pour order.+ - Clearance and thermals are Altium design rules, not the polygon's own. They are written as rules scoped to the polygon (`IsNamedPolygon`, as `apply_pours`' connect rules) and named in `rulesWritten`.+ - The pours are repoured, and `before` / `after` give each one's copper.++- **Three more verbs new in the standard** (EDA Bridge Standard #29):+ - `altium_export_3d` (native): the board in another 3D format than STEP, by Altium's own exporter on File > Export. Parasolid (.x_t) and VRML (.wrl); `step` goes through `export_step`; stl, obj, glb, 3mf, iges and ply are refused by name.+ - The exporter runs through Altium's process launcher, outside the script engine; inside the agent its modal dialogs held the engine and the next verb got no answer.+ - Its dialogs are answered over UI Automation: the file name, then the export options at their defaults. Each exporter is checked by its Save-as type, so a menu in another order is found.+ - Measured: Parasolid wrote lane.x_t (369 KB) in 12 s.+ - `altium_tool_update` (app): `check` gives every Altium on the machine with its exact build, read from its X2.EXE (Altium Designer 26.11.1.5 and Altium Designer Develop 26.9.1.9 on the test laptop). Altium shows what it offers on pages the bridge cannot read: Develop's Extensions & Updates page lists extensions only, and none of its content is in the UI Automation tree. So `offered` is null with the reason rather than a guess, and `apply` is refused by name, listing any unsaved documents. `auto` reads Altium's update-check settings from its preference files.+ - `altium_import_design` (native): `kicad` through Altium's KiCad importer. EAGLE and the Import Wizard's other formats are refused by name for now. EAGLE's wizard is mapped (an importer grid that needs a real click, then its own EAGLE wizard and an old-style file dialog that only Enter answers), and its driver comes in a later build.+- **The standard's engine 0.24.0** (adom-eda-checks, standard 0.30.0, vendored as published), with `bom` and `cross_check`:+ - `altium_bom` now runs on it. The engine's `bom` is a port of this bridge's own, so the lines, checks and files come out the same; Altium still reads every sheet's parts, the board's placement and the project's variants (now passed as the standard's variant row), and writes the files. Altium's own copy of the grouping, checks and file writers is gone.+ - `altium_cross_check {projectPath}` compares every sheet the project lists with its board through the engine, and doesn't count parts kept out of the BOM by their kind as missing. Without `projectPath` it compares one sheet, as before.+- `pour_state` gives each pour an `id`, the standard's handle for a pour: Altium's polygon name, with `#2`, `#3` added when two pours share one.+ ## 0.2.87 - **`schematic_review` reads the drawing** (EDA Bridge Standard #29, engine 0.23.0 / standard 0.28, vendored as published). Each sheet of the project is read live and handed to the engine as its `sheetDrawing` (docs/conventions.md: mm, origin top left, y down: y counts from the sheet's top edge, from its standard style and orientation or its custom size; each entry carries `sizeMm`), so the drawing checks run for Altium too: `dangling_wire_end`, `floating_label` (a label touching no wire or pin) and `overlap` (two symbols drawn over each other).
README.md+9−4@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files), schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -265 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+270 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence. ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`. ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 265 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 270 verbs; each row names the ones behind it (prefix `altium_`). | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 265 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 270 `altium_*` verbs. - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`. <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 265 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 270 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -259,6 +259,11 @@ All 265 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_render_board`: A rendered 3D picture of a board from the top or bottom, by Altium's own 3D print with no window (render_board_3d under the standard's name). - `altium_log_tail`: What Altium said about itself since an offset: its Messages panel (compile, ERC, DRC and script messages) and its own log files, so a verb that looks successful while Altium complains is caught. - `altium_sch_batch`: Apply a list of schematic edits to one sheet in order, all or nothing: each op is a schematic verb with its own arguments, seeing the sheet as the earlier ops left it.+- `altium_import_step`: Place a STEP with the board as free 3D geometry (an enclosure, a bracket, a lid) for fit checks: a 3D body of the board itself on a mechanical layer, belonging to no part, and the parts' bodies it now meets.+- `altium_edit_pours`: Change existing pours in place, without redrawing them: net, layer, hatching, minimum width, grid, dead copper, islands, necks, pouring over same-net objects and pour order; and clearance and thermals, which Altium keeps as design rules scoped to the polygon.+- `altium_export_3d`: The board's 3D model in another format than STEP, by Altium's own exporter (File > Export): Parasolid (.x_t) or VRML (.wrl).+- `altium_tool_update`: Altium's own updates.+- `altium_import_design`: Bring a foreign design into a new Altium project: kicad through Altium's KiCad importer. - `altium_export_library_part`: Export one library part into its own small library files: a symbol library with only its symbol, a footprint library with only its footprint, and its 3D model file. - `altium_create_part_project`: Generate a small real project (schematic and board) around one library part, so the part can be shown and tested in every view: schematic, 2D board and 3D board. - `altium_library_views`: Pictures of library parts for review, each as an image file: the schematic symbol, the footprint (pads and layers), the 3D body seated on the footprint, and the device view that maps symbol pins to pads.
bridge-rs/Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-eda-checks"-version = "0.23.0"+version = "0.24.0" dependencies = [ "roxmltree", "serde_json",
bridge-rs/src/bom.rs+57−243@@ -1,11 +1,12 @@-//! The project BOM Altium itself does not give an AI: every sheet's placed parts with their-//! parameters, the board's placement, variants, grouped by part number, checked for what an order-//! needs, and written as the files distributors and assemblers take (generic, JLCPCB BOM + CPL,-//! Mouser and DigiKey BOM upload). `sheet_params` writes part numbers back onto the sheets.+//! The project BOM Altium itself does not give an AI: every sheet's placed parts with their parameters, the board's+//! placement and the project's variants, read here and handed to the standard's engine (adom-eda-checks `bom`, ported+//! from this file), which groups them by part number, checks them for what an order needs and writes the files+//! distributors and assemblers take (generic, JLCPCB BOM + CPL, Mouser and DigiKey BOM upload). `sheet_params` writes+//! part numbers back onto the sheets. use crate::support::{self, s, timeout_of}; use crate::agent;-use serde_json::{json, Map, Value};-use std::collections::{BTreeMap, HashMap};+use serde_json::{json, Value};+use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -22,24 +23,6 @@ const PACKAGE: &[&str] = &["Package", "Case/Package", "PACKAGE"]; const DNP: &[&str] = &["DNP", "Do Not Populate", "DNF", "Do Not Fit"]; const DESCRIPTION: &[&str] = &["Description", "DESCRIPTION"]; -/// ISch_Component.ComponentKind values that stay out of a BOM: Graphical, Net Tie (no BOM),-/// Standard (no BOM). Mechanical (1), Net Tie (in BOM, 3) and Jumper (6) are bought parts.-const NO_BOM_KINDS: &[i64] = &[2, 4, 5];--fn param(params: &[(String, String)], names: &[&str]) -> String {- for n in names {- if let Some((_, v)) = params.iter().find(|(k, v)| k.eq_ignore_ascii_case(n) && !v.trim().is_empty() && !v.trim().starts_with('=')) {- return v.trim().to_string();- }- }- String::new()-}--fn truthy(v: &str) -> bool {- matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "y" | "dnp" | "x")-}--/// R1 < R2 < R10 < R10A: the letters, then the number, then the rest. pub fn natural_key(d: &str) -> (String, u64, String) { let pre: String = d.chars().take_while(|c| !c.is_ascii_digit()).collect(); let rest = &d[pre.len()..];@@ -89,148 +72,8 @@ pub fn parse_project(text: &str, dir: &Path) -> Project { p } -/// One placed part, merged from its sheet (parameters) and the board (footprint, placement).-#[derive(Debug, Clone, Default)]-pub struct Part {- pub designator: String,- pub comment: String,- pub description: String,- pub lib_ref: String,- pub sheet: String,- pub kind: i64,- pub params: Vec<(String, String)>,- pub footprint: String,- pub placed: Option<(f64, f64, f64, String)>,- pub dnp: bool,- pub alternate: String,- /// a workspace-managed part (Altium 365 / a content vault): its item GUID and source library- pub item_guid: String,- pub source_lib: String,-}--impl Part {- fn get(&self, names: &[&str]) -> String { param(&self.params, names) }- pub fn mpn(&self) -> String { self.get(MPN) }- fn value(&self) -> String { let v = self.get(VALUE); if v.is_empty() { self.comment.clone() } else { v } }- /// Copper test pads, fiducials and the like carry an MPN that says nothing is bought ("none (PCB copper)"):- /// they stay in the BOM, marked, and stay out of the ordering and assembly files.- pub fn not_purchased(&self) -> bool {- // in the MPN or the manufacturer (the Adom test pads say Manufacturer "none (PCB copper)")- [self.mpn(), self.get(MFR)].iter().any(|v| {- let m = v.trim().to_ascii_lowercase();- m.starts_with("none") || m == "n/a" || m == "na" || m == "-" || m.contains("pcb copper") || m.contains("not purchased") || m.contains("no part")- })- }-}--const FIELDS: &[(&str, &[&str])] = &[("mpn", MPN), ("manufacturer", MFR), ("mouser", MOUSER), ("digikey", DIGIKEY), ("lcsc", LCSC)];--/// Group the fitted parts: one line per manufacturer part number, else per comment + footprint.-/// Returns (lines, checks).-pub fn group(parts: &[Part]) -> (Vec<Value>, Value) {- let mut groups: BTreeMap<String, Vec<&Part>> = BTreeMap::new();- for p in parts.iter().filter(|p| !p.dnp && !NO_BOM_KINDS.contains(&p.kind)) {- let m = p.mpn();- let key = if m.is_empty() { format!("~{}|{}", p.value().to_ascii_uppercase(), p.footprint.to_ascii_uppercase()) } else { format!("{}|{}", m.to_ascii_uppercase(), p.get(MFR).to_ascii_uppercase()) };- groups.entry(key).or_default().push(p);- }- let mut lines = Vec::new();- let mut inconsistent = Vec::new();- for (_, mut g) in groups {- g.sort_by_key(|p| natural_key(&p.designator));- let refs: Vec<String> = g.iter().map(|p| p.designator.clone()).collect();- let mut line = Map::new();- line.insert("quantity".into(), json!(g.len()));- line.insert("designators".into(), json!(refs));- for (name, names) in FIELDS {- let vals: Vec<String> = g.iter().map(|p| p.get(names)).collect();- let mut distinct: Vec<&String> = vals.iter().filter(|v| !v.is_empty()).collect();- distinct.sort(); distinct.dedup();- if distinct.len() > 1 { inconsistent.push(json!({"field": name, "designators": refs, "values": distinct})); }- line.insert((*name).into(), json!(distinct.first().map(|s| s.as_str()).unwrap_or("")));- }- let first = g[0];- let mut fps: Vec<&str> = g.iter().map(|p| p.footprint.as_str()).filter(|f| !f.is_empty()).collect();- fps.sort(); fps.dedup();- if fps.len() > 1 { inconsistent.push(json!({"field": "footprint", "designators": refs, "values": fps})); }- line.insert("value".into(), json!(first.value()));- line.insert("comment".into(), json!(first.comment));- line.insert("description".into(), json!(if first.description.is_empty() { first.get(DESCRIPTION) } else { first.description.clone() }));- line.insert("sourceLibrary".into(), json!(first.source_lib));- line.insert("managed".into(), json!(!first.item_guid.is_empty()));- line.insert("footprint".into(), json!(fps.first().copied().unwrap_or("")));- line.insert("package".into(), json!(first.get(PACKAGE)));- line.insert("libReference".into(), json!(first.lib_ref));- line.insert("purchase".into(), json!(!first.not_purchased()));- lines.push(Value::Object(line));- }- lines.sort_by_key(|l| natural_key(l["designators"][0].as_str().unwrap_or("")));- let fitted: Vec<&Part> = parts.iter().filter(|p| !p.dnp && !NO_BOM_KINDS.contains(&p.kind) && !p.not_purchased()).collect();- let mut not_purchased: Vec<String> = parts.iter().filter(|p| !p.dnp && !NO_BOM_KINDS.contains(&p.kind) && p.not_purchased()).map(|p| p.designator.clone()).collect();- not_purchased.sort_by_key(|d| natural_key(d));- let missing = |names: &[&str]| -> Vec<String> {- let mut v: Vec<String> = fitted.iter().filter(|p| p.get(names).is_empty()).map(|p| p.designator.clone()).collect();- v.sort_by_key(|d| natural_key(d)); v- };- let mut dnp: Vec<String> = parts.iter().filter(|p| p.dnp).map(|p| p.designator.clone()).collect();- dnp.sort_by_key(|d| natural_key(d));- let mut excluded: Vec<String> = parts.iter().filter(|p| !p.dnp && NO_BOM_KINDS.contains(&p.kind)).map(|p| p.designator.clone()).collect();- excluded.sort_by_key(|d| natural_key(d));- let checks = json!({- "missingMpn": missing(MPN), "missingManufacturer": missing(MFR),- "missingPartNumbers": {"mouser": missing(MOUSER), "digikey": missing(DIGIKEY), "lcsc": missing(LCSC)},- "inconsistent": inconsistent, "dnp": dnp, "excludedKinds": excluded, "notPurchased": not_purchased,- });- let mut checks = checks;- // JLCPCB assembly places only what it can source by LCSC number: every other purchased line is consigned or blocks- let no_lcsc: Vec<Value> = lines.iter().filter(|l| l["purchase"] == json!(true) && st(&l["lcsc"]).is_empty())- .map(|l| json!({"designators": l["designators"], "mpn": l["mpn"], "value": l["value"]})).collect();- checks["jlcpcb"] = json!({"ready": no_lcsc.is_empty(), "linesWithoutLcsc": no_lcsc});- (lines, checks)-}--fn csv_cell(s: &str) -> String {- if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() }-}--fn csv(rows: &[Vec<String>]) -> String {- rows.iter().map(|r| r.iter().map(|c| csv_cell(c)).collect::<Vec<_>>().join(",")).collect::<Vec<_>>().join("\r\n") + "\r\n"-}- fn st(v: &Value) -> String { v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string()) } -/// The files, as (name, text). `boards` multiplies the quantities of the ordering files.-pub fn files(lines: &[Value], parts: &[Part], boards: u64) -> Vec<(String, String)> {- let refs = |l: &Value| l["designators"].as_array().map(|a| a.iter().map(st).collect::<Vec<_>>().join(",")).unwrap_or_default();- let mut out = Vec::new();- let mut rows = vec![["Line", "Quantity", "Designators", "Value", "Comment", "Description", "Footprint", "Package", "MPN", "Manufacturer", "Mouser Part #", "DigiKey Part #", "LCSC Part #"].map(String::from).to_vec()];- for (i, l) in lines.iter().enumerate() {- rows.push(vec![(i + 1).to_string(), st(&l["quantity"]), refs(l), st(&l["value"]), st(&l["comment"]), st(&l["description"]), st(&l["footprint"]), st(&l["package"]), st(&l["mpn"]), st(&l["manufacturer"]), st(&l["mouser"]), st(&l["digikey"]), st(&l["lcsc"])]);- }- out.push(("bom.csv".to_string(), csv(&rows)));- // JLCPCB assembly: their BOM and CPL column names, mm, Top/Bottom- let mut j = vec![["Comment", "Designator", "Footprint", "LCSC Part #"].map(String::from).to_vec()];- for l in lines.iter().filter(|l| l["purchase"] != json!(false)) { j.push(vec![st(&l["value"]), refs(l), st(&l["footprint"]), st(&l["lcsc"])]); }- out.push(("bom-jlcpcb.csv".to_string(), csv(&j)));- let mut c = vec![["Designator", "Mid X", "Mid Y", "Layer", "Rotation"].map(String::from).to_vec()];- let mut placed: Vec<&Part> = parts.iter().filter(|p| !p.dnp && !NO_BOM_KINDS.contains(&p.kind) && !p.not_purchased() && p.placed.is_some()).collect();- placed.sort_by_key(|p| natural_key(&p.designator));- for p in placed {- let (x, y, r, side) = p.placed.clone().unwrap();- c.push(vec![p.designator.clone(), format!("{x:.4}mm"), format!("{y:.4}mm"), if side == "bottom" { "Bottom".into() } else { "Top".into() }, format!("{}", (r.rem_euclid(360.0) * 1000.0).round() / 1000.0)]);- }- out.push(("cpl-jlcpcb.csv".to_string(), csv(&c)));- // distributor BOM tools (Mouser BOM Tool, DigiKey myLists / BOM Manager) map these headers directly- for (name, field, header) in [("bom-mouser.csv", "mouser", "Mouser Part Number"), ("bom-digikey.csv", "digikey", "Digi-Key Part Number")] {- let mut m = vec![vec![header.to_string(), "Manufacturer Part Number".into(), "Manufacturer".into(), "Quantity".into(), "Customer Reference".into()]];- for l in lines.iter().filter(|l| l["purchase"] != json!(false) && (!st(&l[field]).is_empty() || !st(&l["mpn"]).is_empty())) {- m.push(vec![st(&l[field]), st(&l["mpn"]), st(&l["manufacturer"]), (l["quantity"].as_u64().unwrap_or(0) * boards.max(1)).to_string(), refs(l)]);- }- out.push((name.to_string(), csv(&m)));- }- out-}- fn sheet_parts(sheet: &str, timeout: Duration) -> Result<(String, Vec<Value>), Value> { if let Some(first) = support::must_open(sheet, 60) { // once more, longer: right after an OutJob run Altium can still be busy, and the sheet open timed out@@ -271,7 +114,10 @@ pub fn bom(args: &Value) -> Value { }, None => None, };- let mut parts: BTreeMap<String, Part> = BTreeMap::new();+ // every sheet's parts as read (the standard's sheetParts: designator, comment, description, libReference, kind,+ // params), the board's placement, and the variant: the engine (adom-eda-checks bom, ported from this file) groups+ // them, checks them and writes the order files' text+ let mut sheet_parts_all: Vec<Value> = Vec::new(); let mut sheets_read = Vec::new(); // altium_progress shows which sheet a long read is on (a large project reads dozens) crate::progress::begin("bom", "warm", "reading the schematic sheets", "bridge");@@ -281,21 +127,12 @@ pub fn bom(args: &Value) -> Value { crate::progress::step("bom", &format!("sheet {} of {n_sheets}: {name}", i + 1), Some((i * 90 / n_sheets.max(1)) as i64), None, "bridge"); let (doc, comps) = match sheet_parts(sheet, timeout) { Ok(x) => x, Err(e) => { crate::progress::end("bom", "bridge"); return json!({"success": false, "errorCode": "sheet_read_failed", "sheet": sheet, "reply": e}) } }; sheets_read.push(json!({"sheet": doc, "components": comps.len()}));- for c in comps {- let d = st(&c["designator"]);- if d.is_empty() || d.ends_with('?') { continue; }- let params: Vec<(String, String)> = c["params"].as_array().cloned().unwrap_or_default().iter().filter(|p| p.get("value").is_some()).map(|p| (st(&p["name"]), st(&p["value"]))).collect();- // a multi-part component appears once per part: keep the first, add any parameter it lacks- let e = parts.entry(d.to_ascii_uppercase()).or_insert_with(|| Part {- designator: d.clone(), comment: st(&c["comment"]), description: st(&c["description"]), lib_ref: st(&c["libReference"]),- sheet: doc.clone(), kind: c["kind"].as_i64().unwrap_or(0), item_guid: st(&c["itemGuid"]), source_lib: st(&c["sourceLibrary"]), ..Default::default() });- for (k, v) in params { if !e.params.iter().any(|(k2, _)| k2.eq_ignore_ascii_case(&k)) { e.params.push((k, v)); } }- }+ for mut c in comps { c["sheet"] = json!(doc); sheet_parts_all.push(c); } }- // the board: footprint and placement of each part- let mut board_only = Vec::new();+ // the board: footprint and placement of each part, from its origin let board = s(args, "pcbPath").or_else(|| project.boards.first().cloned()); let mut board_read = Value::Null;+ let mut board_json = Value::Null; if let Some(b) = &board { crate::progress::step("bom", "reading the board's placement", Some(92), None, "bridge"); if let Some(e) = support::must_open(b, 60) { crate::progress::end("bom", "bridge"); return json!({"success": false, "errorCode": "board_open_failed", "board": b, "reply": e}); }@@ -306,44 +143,34 @@ pub fn bom(args: &Value) -> Value { return json!({"success": false, "errorCode": "board_read_failed", "board": b, "reply": r}); }; board_read = json!({"board": b, "components": comps.len()});- for c in comps {- // [designator, pattern, x, y (raw from the origin, 10000 per mil), rotation (millidegrees), bottom]- let d = st(&c[0]);- let mm = |v: &Value| (v.as_f64().unwrap_or(0.0) / 10000.0 * 0.0254 * 10000.0).round() / 10000.0;- let placed = Some((mm(&c[2]), mm(&c[3]), c[4].as_f64().unwrap_or(0.0) / 1000.0, if c[5].as_bool() == Some(true) { "bottom".to_string() } else { "top".to_string() }));- match parts.get_mut(&d.to_ascii_uppercase()) {- Some(p) => { p.footprint = st(&c[1]); p.placed = placed; }- None => board_only.push(d),- }- }- }- let mut not_on_board: Vec<String> = if board.is_some() { parts.values().filter(|p| p.placed.is_none() && !NO_BOM_KINDS.contains(&p.kind)).map(|p| p.designator.clone()).collect() } else { vec![] };- not_on_board.sort_by_key(|d| natural_key(d));- board_only.sort_by_key(|d| natural_key(d));- for p in parts.values_mut() {- if truthy(&p.get(DNP)) { p.dnp = true; }- if p.get(&["Fitted"]).eq_ignore_ascii_case("false") { p.dnp = true; }- if let Some((_, m)) = variant {- if let Some((kind, alt)) = m.get(&p.designator.to_ascii_uppercase()) {- if *kind == 1 { p.dnp = true; } else if !alt.is_empty() { p.alternate = alt.clone(); }- }- }+ // [designator, pattern, x, y (raw from the origin, 10000 per mil), rotation (millidegrees), bottom, ...]+ let mm = |v: &Value| (v.as_f64().unwrap_or(0.0) / 10000.0 * 0.0254 * 10000.0).round() / 10000.0;+ let rows: Vec<Value> = comps.iter().map(|c| json!({"ref": c[0], "pattern": c[1], "x": mm(&c[2]), "y": mm(&c[3]),+ "rotation": c[4].as_f64().unwrap_or(0.0) / 1000.0, "side": if c[5].as_bool() == Some(true) { "bottom" } else { "top" }})).collect();+ board_json = json!({"components": rows}); } crate::progress::end("bom", "bridge");- let list: Vec<Part> = parts.values().cloned().collect();- let (lines, mut checks) = group(&list);- checks["sheetNotOnBoard"] = json!(not_on_board);- checks["boardNotOnSheet"] = json!(board_only);- let alternates: Vec<Value> = list.iter().filter(|p| !p.alternate.is_empty()).map(|p| json!({"designator": p.designator, "alternatePart": p.alternate})).collect();- let fitted = list.iter().filter(|p| !p.dnp && !NO_BOM_KINDS.contains(&p.kind)).count();+ // the variant as the standard's row: its not-fitted parts and alternates+ let variant_row = variant.map(|(name, m)| json!({"name": name,+ "notFitted": m.iter().filter(|(_, (k, _))| *k == 1).map(|(d, _)| d.clone()).collect::<Vec<_>>(),+ "alternates": m.iter().filter(|(_, (k, a))| *k != 1 && !a.is_empty()).map(|(d, (_, a))| json!({"designator": d, "part": a})).collect::<Vec<_>>()})); let boards = args.get("boards").and_then(|v| v.as_u64()).unwrap_or(1);+ let mut input = json!({"sheetParts": sheet_parts_all, "args": {"boards": boards}});+ if !board_json.is_null() { input["board"] = board_json; }+ if let Some(v) = variant_row { input["args"]["variant"] = v; }+ let r = adom_eda_checks::bom::bom(&input);+ if r.get("success").and_then(|b| b.as_bool()) != Some(true) { return r; }+ let lines: Vec<Value> = r["lines"].as_array().cloned().unwrap_or_default();+ let checks = r["checks"].clone();+ let alternates = r["alternates"].clone();+ let fitted = r["fittedParts"].as_u64().unwrap_or(0); let mut written = Vec::new(); if args.get("write").and_then(|b| b.as_bool()) != Some(false) { let out_dir = s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| dir.join("BOM")); if let Err(e) = std::fs::create_dir_all(&out_dir) { return json!({"success": false, "errorCode": "output_dir", "error": format!("{}: {e}", out_dir.display())}); }- for (name, body) in files(&lines, &list, boards) {- let p = out_dir.join(&name);- if let Err(e) = std::fs::write(&p, body) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", p.display())}); }+ for f in r["files"].as_array().cloned().unwrap_or_default() {+ let p = out_dir.join(f["name"].as_str().unwrap_or("bom.txt"));+ if let Err(e) = std::fs::write(&p, f["text"].as_str().unwrap_or("")) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", p.display())}); } written.push(p.to_string_lossy().to_string()); } let j = out_dir.join("bom.json");@@ -420,8 +247,15 @@ mod tests { const PRJ: &str = "[Design]\r\nVersion=1.0\r\n\r\n[Document1]\r\nDocumentPath=Power.SchDoc\r\n\r\n[Document2]\r\nDocumentPath=Sub\\IO.SchDoc\r\n\r\n[Document3]\r\nDocumentPath=Board.PcbDoc\r\n\r\n[DeviceSheet1]\r\nDocumentPath=Managed\\Sheets\\AB\\Osc.SchDoc\r\n\r\n[DeviceSheet2]\r\nDocumentPath=Managed\\Sheets\\AB\\Osc.Harness\r\n\r\n[ProjectVariant1]\r\nDescription=Lite\r\nVariationCount=2\r\nVariation1=Designator=R2|UniqueId=\\ABC|Kind=1|AlternatePart=\r\nVariation2=Designator=U1|UniqueId=\\DEF|Kind=2|AlternatePart=TPS54302\r\n"; - fn part(d: &str, params: &[(&str, &str)], fp: &str) -> Part {- Part { designator: d.into(), comment: "c".into(), footprint: fp.into(), params: params.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(), placed: Some((1.0, 2.0, 90.0, "top".into())), ..Default::default() }+ /// The engine's bom on parts as Altium reads them: sheet components with their parameters, and the board's placement+ /// (each at 1, 2 mm, turned 90). Answers (lines, checks, files by name).+ fn run(parts: &[(&str, &[(&str, &str)], &str, i64)], boards: u64) -> (Vec<Value>, Value, HashMap<String, String>) {+ let sheet: Vec<Value> = parts.iter().map(|(d, ps, _, kind)| json!({"designator": d, "comment": "c", "libReference": "LIB", "kind": kind,+ "params": ps.iter().map(|(n, v)| json!({"name": n, "value": v})).collect::<Vec<_>>()})).collect();+ let board: Vec<Value> = parts.iter().filter(|(_, _, fp, _)| !fp.is_empty()).map(|(d, _, fp, _)| json!({"ref": d, "pattern": fp, "x": 1.0, "y": 2.0, "rotation": 90.0, "side": "top"})).collect();+ let r = adom_eda_checks::bom::bom(&json!({"sheetParts": sheet, "board": {"components": board}, "args": {"boards": boards}}));+ let files = r["files"].as_array().cloned().unwrap_or_default().iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["text"].as_str().unwrap().to_string())).collect();+ (r["lines"].as_array().cloned().unwrap_or_default(), r["checks"].clone(), files) } #[test]@@ -439,16 +273,13 @@ mod tests { #[test] fn lines_group_by_mpn_across_parameter_names() {- let parts = vec![- part("R10", &[("MPN", "RC0402-10K"), ("Manufacturer", "Yageo"), ("Mouser Part #", "603-RC0402")], "R0402"),- part("R2", &[("Manufacturer Part Number", "RC0402-10K"), ("Manufacturer", "Yageo")], "R0402"),- part("C1", &[("Value", "100n")], "C0402"),- part("C2", &[("Value", "100n")], "C0402"),- part("TP1", &[("DNP", "yes")], "TP"),- ];- let mut parts = parts;- parts[4].dnp = true;- let (lines, checks) = group(&parts);+ let (lines, checks, _) = run(&[+ ("R10", &[("MPN", "RC0402-10K"), ("Manufacturer", "Yageo"), ("Mouser Part #", "603-RC0402")], "R0402", 0),+ ("R2", &[("Manufacturer Part Number", "RC0402-10K"), ("Manufacturer", "Yageo")], "R0402", 0),+ ("C1", &[("Value", "100n")], "C0402", 0),+ ("C2", &[("Value", "100n")], "C0402", 0),+ ("TP1", &[("DNP", "yes")], "TP", 0),+ ], 1); assert_eq!(lines.len(), 2); assert_eq!(lines[0]["designators"], json!(["C1", "C2"])); assert_eq!(lines[1]["designators"], json!(["R2", "R10"]), "natural order");@@ -462,25 +293,21 @@ mod tests { #[test] fn a_line_with_two_footprints_is_inconsistent() {- let parts = vec![part("R1", &[("MPN", "X")], "R0402"), part("R2", &[("MPN", "X")], "R0603")];- let (_, checks) = group(&parts);+ let (_, checks, _) = run(&[("R1", &[("MPN", "X")], "R0402", 0), ("R2", &[("MPN", "X")], "R0603", 0)], 1); assert_eq!(checks["inconsistent"][0]["field"], json!("footprint")); } #[test] fn no_bom_kinds_stay_out() {- let mut logo = part("LOGO1", &[], "");- logo.kind = 2;- let (lines, checks) = group(&[part("R1", &[("MPN", "X")], "R0402"), logo]);+ // Altium's Graphical kind (2), as ComponentKind reads it+ let (lines, checks, _) = run(&[("R1", &[("MPN", "X")], "R0402", 0), ("LOGO1", &[], "", 2)], 1); assert_eq!(lines.len(), 1); assert_eq!(checks["excludedKinds"], json!(["LOGO1"])); } #[test] fn files_carry_the_columns_each_site_takes() {- let parts = vec![part("U1", &[("MPN", "TPS54202DDCR"), ("Manufacturer", "TI"), ("LCSC Part #", "C191884"), ("Mouser Part #", "595-TPS54202DDCR")], "SOT-23-6")];- let (lines, _) = group(&parts);- let f: HashMap<String, String> = files(&lines, &parts, 5).into_iter().collect();+ let (_, _, f) = run(&[("U1", &[("MPN", "TPS54202DDCR"), ("Manufacturer", "TI"), ("LCSC Part #", "C191884"), ("Mouser Part #", "595-TPS54202DDCR")], "SOT-23-6", 0)], 5); assert!(f["bom-jlcpcb.csv"].starts_with("Comment,Designator,Footprint,LCSC Part #\r\n")); assert!(f["bom-jlcpcb.csv"].contains("U1,SOT-23-6,C191884")); assert!(f["cpl-jlcpcb.csv"].contains("U1,1.0000mm,2.0000mm,Top,90"));@@ -490,27 +317,14 @@ mod tests { #[test] fn copper_pads_stay_out_of_the_order_files() {- let mut tp = part("TP5", &[("MPN", "Adom_TestPoint_D0.5mm"), ("Manufacturer", "none (PCB copper)")], "TESTPOINT_PAD");- tp.placed = Some((1.0, 2.0, 0.0, "top".into()));- let mut r = part("R1", &[("MPN", "X"), ("LCSC Part #", "C1")], "R0402");- r.placed = Some((3.0, 4.0, 0.0, "top".into()));- let c = part("C1", &[("MPN", "Y")], "C0402");- let parts = vec![tp, r, c];- let (lines, checks) = group(&parts);+ let (_, checks, f) = run(&[("TP5", &[("MPN", "Adom_TestPoint_D0.5mm"), ("Manufacturer", "none (PCB copper)")], "TESTPOINT_PAD", 0),+ ("R1", &[("MPN", "X"), ("LCSC Part #", "C1")], "R0402", 0), ("C1", &[("MPN", "Y")], "C0402", 0)], 1); assert_eq!(checks["notPurchased"], json!(["TP5"])); assert_eq!(checks["jlcpcb"]["ready"], json!(false)); assert_eq!(checks["jlcpcb"]["linesWithoutLcsc"][0]["designators"], json!(["C1"])); assert!(!checks["missingPartNumbers"]["mouser"].as_array().unwrap().contains(&json!("TP5")));- let f: std::collections::HashMap<String, String> = files(&lines, &parts, 1).into_iter().collect(); assert!(!f["bom-jlcpcb.csv"].contains("TP5")); assert!(!f["cpl-jlcpcb.csv"].contains("TP5")); assert!(f["bom.csv"].contains("TP5")); }-- #[test]- fn csv_quotes_what_needs_it() {- assert_eq!(csv_cell("R1,R2"), "\"R1,R2\"");- assert_eq!(csv_cell("10\" cable"), "\"10\"\" cable\"");- assert_eq!(csv_cell("plain"), "plain");- } }
bridge-rs/src/editpours.rsadded+138@@ -0,0 +1,138 @@+//! edit_pours: change existing pours in place (EDA Bridge Standard #29): net, layer, hatching, minimum width, grid,+//! dead copper, islands, necks, pouring over same-net objects, pour order; and clearance and thermals. In Altium the+//! last two are not the polygon's own: they come from design rules, so they are written as rules scoped to the+//! polygon (IsNamedPolygon, as apply_pours' connect rules) and named in rulesWritten. Pours are named by pour_state's+//! name, or by net and layer.+use serde_json::{json, Value};+use std::time::Duration;++const PER_MM: f64 = 10000.0 / 0.0254;++/// The agent's lines ("name|key|value") for one pour's changes, and the clearance it wants as a rule. Pure.+pub fn ops_for(name: &str, set: &Value) -> Result<(Vec<String>, Option<f64>), String> {+ let mut out = Vec::new();+ let raw = |mm: f64| ((mm * PER_MM).round() as i64).to_string();+ let push = |out: &mut Vec<String>, k: &str, v: String| out.push(format!("{name}|{k}|{v}"));+ let Some(m) = set.as_object() else { return Err("set is an object of the properties to change".into()) };+ let mut clearance = None;+ for (k, v) in m {+ match k.as_str() {+ "net" => push(&mut out, "net", v.as_str().ok_or("net is a name")?.to_string()),+ "layer" => push(&mut out, "layer", crate::routing::layer_id(v).ok_or(format!("unknown layer {v}"))?.to_string()),+ "hatch" => { let h = v.as_str().unwrap_or(""); if !["solid", "45", "90", "none"].contains(&h) { return Err("hatch is solid, 45, 90 or none".into()); } push(&mut out, "hatch", h.into()) }+ "minWidthMm" => push(&mut out, "track", raw(v.as_f64().ok_or("minWidthMm is mm")?)),+ "gridMm" => push(&mut out, "grid", raw(v.as_f64().ok_or("gridMm is mm")?)),+ "removeDead" => push(&mut out, "dead", if v.as_bool() == Some(true) { "1" } else { "0" }.into()),+ "removeIslands" => push(&mut out, "islands", if v.as_bool() == Some(true) { "1" } else { "0" }.into()),+ "neckMm" => push(&mut out, "neck", raw(v.as_f64().unwrap_or(0.0))),+ "pourOverSameNet" => push(&mut out, "over", if v.as_bool() == Some(false) { "none" } else { "same" }.into()),+ "pourIndex" | "priority" => push(&mut out, "index", v.as_i64().ok_or("pourIndex is an integer")?.to_string()),+ "clearanceMm" => clearance = Some(v.as_f64().ok_or("clearanceMm is mm")?),+ "connect" => {+ let style = match v.as_str().unwrap_or("").to_ascii_lowercase().as_str() { "direct" | "solid" => "D", "relief" | "thermal" => "R", "none" => "N", o => return Err(format!("connect is direct, relief or none (got {o})")) };+ let w = m.get("reliefWidthMm").and_then(|x| x.as_f64()).unwrap_or(0.254);+ let g = m.get("reliefGapMm").and_then(|x| x.as_f64()).unwrap_or(0.254);+ let e = m.get("reliefEntries").and_then(|x| x.as_i64()).unwrap_or(4);+ if e != 2 && e != 4 { return Err("reliefEntries is 2 or 4".into()); }+ push(&mut out, "connect", format!("{style},{},{},{e}", raw(w), raw(g)));+ }+ "reliefWidthMm" | "reliefGapMm" | "reliefEntries" => { if !m.contains_key("connect") { return Err(format!("{k} goes with connect")); } }+ o => return Err(format!("{o} is not a pour property this verb changes")),+ }+ }+ Ok((out, clearance))+}++/// The pours a target names: by name, or every pour on a net (and layer). Pure.+pub fn targets(t: &Value, zones: &[Value]) -> Vec<String> {+ // pour_state's id first (the standard's handle: Altium's name, #n when two pours share one), then its name+ if let Some(id) = t["id"].as_str() {+ return zones.iter().filter(|z| z["id"].as_str() == Some(id)).filter_map(|z| z["name"].as_str().map(str::to_string)).take(1).collect();+ }+ if let Some(n) = t["name"].as_str() {+ return zones.iter().filter(|z| z["name"].as_str() == Some(n)).filter_map(|z| z["name"].as_str().map(str::to_string)).collect();+ }+ let net = t["net"].as_str();+ let layer = t.get("layer").and_then(crate::routing::layer_id);+ zones.iter().filter(|z| net.map(|n| z["net"].as_str() == Some(n)).unwrap_or(false) && layer.map(|l| z["layerId"].as_i64() == Some(l)).unwrap_or(true))+ .filter_map(|z| z["name"].as_str().map(str::to_string)).collect()+}++fn zones(ps: &Value) -> Vec<Value> { ["zones", "unfilled"].iter().flat_map(|k| ps[*k].as_array().cloned().unwrap_or_default()).collect() }++/// altium_edit_pours {filePath, pours: [{name | net + layer?, set: {...}}], repour?, expectedRevision?}+pub fn edit_pours(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let Some(board) = crate::support::s(args, "filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});+ };+ let Some(want) = args.get("pours").and_then(|v| v.as_array()).filter(|a| !a.is_empty()).cloned() else {+ return json!({"success": false, "errorCode": "bad_args", "error": "pours: [{name (from pour_state) | net + layer?, set: {...}}] is required"});+ };+ if let Some(e) = crate::support::must_open(&board, 60) { return e; }+ if let Err(e) = crate::routing::guarded(args) { return e; }+ let before = crate::routing::pour_state(&json!({}));+ let all = zones(&before);+ let (mut lines, mut rules, mut touched) = (Vec::new(), Vec::new(), Vec::new());+ for (i, t) in want.iter().enumerate() {+ let names = targets(t, &all);+ if names.is_empty() { return json!({"success": false, "errorCode": "no_such_pour", "index": i, "error": format!("no pour matches {t}"), "pours": all.iter().map(|z| json!({"name": z["name"], "net": z["net"], "layer": z["layer"]})).collect::<Vec<_>>()}); }+ for n in names {+ let (ops, clearance) = match ops_for(&n, &t["set"]) { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "bad_args", "index": i, "error": e, "mutated": false}) };+ lines.extend(ops);+ if let Some(c) = clearance { rules.push((n.clone(), c)); }+ if !touched.contains(&n) { touched.push(n); }+ }+ }+ let mut results = Value::Null;+ if !lines.is_empty() {+ let r = crate::agent::call("edit_pour", &[], Some(&lines.join("\n")), Duration::from_secs(180));+ let d = r.get("data").cloned().unwrap_or(Value::Null);+ if d["ok"] != json!(true) { return json!({"success": false, "errorCode": "edit_failed", "error": d.get("error").cloned().unwrap_or(json!("the pours were not edited")), "reply": r}); }+ results = d["results"].clone();+ }+ // clearance is a rule in Altium: one per pour, scoped to the polygon itself+ let mut written = Vec::new();+ for (n, gap) in &rules {+ let r = crate::verbs::dispatch("add_rule", &json!({"kind": "clearance", "name": format!("Pour {n}"), "scope1": format!("IsNamedPolygon('{n}')"), "scope2": "All", "gap": gap}), &[]);+ written.push(json!({"pour": n, "rule": format!("Adom Pour {n}"), "kind": "clearance", "gapMm": gap, "ok": r.get("success").and_then(|b| b.as_bool()) == Some(true), "error": r.get("error")}));+ }+ let after = if args.get("repour").and_then(|v| v.as_bool()) != Some(false) { crate::routing::repour(&json!({})); crate::routing::pour_state(&json!({})) } else { crate::routing::pour_state(&json!({})) };+ let pick = |ps: &Value| -> Vec<Value> { zones(ps).into_iter().filter(|z| z["name"].as_str().map(|n| touched.iter().any(|t| t == n)).unwrap_or(false))+ .map(|z| json!({"name": z["name"], "net": z["net"], "layer": z["layer"], "pourIndex": z["pourIndex"], "filled": z["filled"], "filledMm2": z["filledMm2"], "hatchedPieces": z["hatchedPieces"], "islands": z["islands"]})).collect() };+ let failed: Vec<&Value> = results.as_array().map(|a| a.iter().filter(|x| x.as_str().map(|s| s.starts_with("err")).unwrap_or(false)).collect()).unwrap_or_default();+ json!({"success": failed.is_empty() && written.iter().all(|w| w["ok"] == json!(true)), "mutated": true, "edited": touched, "results": results, "rulesWritten": written,+ "before": pick(&before), "after": pick(&after),+ "_hint": "Each pour is changed in place and repoured (repour:false skips it). Clearance and thermals are Altium design rules, not the polygon's own: rulesWritten names the rules scoped to each polygon (connect writes its AdomPC rule). The board is left unsaved: altium_save keeps it."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_pours_changes_as_agent_lines() {+ let (ops, clr) = ops_for("GND top", &json!({"net": "GND", "hatch": "45", "removeIslands": true, "pourIndex": 2, "clearanceMm": 0.3,+ "connect": "relief", "reliefWidthMm": 0.254, "reliefEntries": 2})).unwrap();+ assert_eq!(clr, Some(0.3));+ assert!(ops.contains(&"GND top|net|GND".to_string()));+ assert!(ops.contains(&"GND top|hatch|45".to_string()));+ assert!(ops.contains(&"GND top|islands|1".to_string()));+ assert!(ops.contains(&"GND top|index|2".to_string()));+ assert!(ops.iter().any(|o| o.starts_with("GND top|connect|R,100000,100000,2")), "{ops:?}");+ assert!(ops_for("X", &json!({"hatch": "zigzag"})).is_err());+ assert!(ops_for("X", &json!({"reliefGapMm": 0.2})).is_err(), "relief settings go with connect");+ assert!(ops_for("X", &json!({"colour": "red"})).is_err());+ }++ #[test]+ fn targets_by_name_or_net_and_layer() {+ let z = |n: &str, net: &str, l: i64| json!({"id": n, "name": n, "net": net, "layerId": l});+ let zones = vec![z("A", "GND", 1), z("B", "GND", 32), z("C", "3V3", 1)];+ assert_eq!(targets(&json!({"name": "B"}), &zones), ["B"]);+ assert_eq!(targets(&json!({"id": "C"}), &zones), ["C"]);+ assert_eq!(targets(&json!({"net": "GND"}), &zones), ["A", "B"]);+ assert_eq!(targets(&json!({"net": "GND", "layer": "B.Cu"}), &zones), ["B"]);+ assert!(targets(&json!({"name": "Z"}), &zones).is_empty());+ }+}
bridge-rs/src/geom3d.rsadded+234@@ -0,0 +1,234 @@+//! The board's 3D outside the parts: import_step places a STEP with the board as free geometry (an enclosure, a+//! bracket) for fit checks, the standard's import_step (EDA Bridge Standard #29). It is a 3D body of the board itself,+//! on a mechanical layer, belonging to no part (add_body puts a model on one footprint instead), and the answer says at+//! once which parts' bodies it now meets.+use serde_json::{json, Value};+use std::time::Duration;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++/// The parts' bodies a box meets: plan overlap more than 0.01 mm both ways and height overlap, on the same side. Pure.+pub fn meets(bx: [f64; 4], z: (f64, f64), side: &str, bodies: &[Value]) -> Vec<Value> {+ let mut out = Vec::new();+ for b in bodies {+ if b["side"].as_str().unwrap_or("top") != side || b["ref"].as_str().unwrap_or("").is_empty() { continue; }+ let (ox, oy) = (bx[2].min(f(&b["x1"])) - bx[0].max(f(&b["x0"])), bx[3].min(f(&b["y1"])) - bx[1].max(f(&b["y0"])));+ let oz = z.1.min(f(&b["z1"])) - z.0.max(f(&b["z0"]));+ if ox > 0.01 && oy > 0.01 && oz > 0.0 {+ out.push(json!({"ref": b["ref"], "overlapMm": [r3(ox), r3(oy), r3(oz)]}));+ }+ }+ out+}++/// altium_import_step {filePath, stepPath, at?: [x, y] mm, rotation?: [rx, ry, rz] degrees, standoffMm?, side?, layer?}+pub fn import_step(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let s = |k: &str| crate::support::s(args, k);+ let Some(board) = s("filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});+ };+ let Some(step) = s("stepPath").or_else(|| s("path")).filter(|p| { let l = p.to_lowercase(); l.ends_with(".step") || l.ends_with(".stp") }) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "stepPath (a .step or .stp file on this machine) is required"});+ };+ let side = s("side").unwrap_or_else(|| "top".into()).to_lowercase();+ if side != "top" && side != "bottom" { return json!({"success": false, "errorCode": "bad_args", "error": "side is top or bottom"}); }+ let mech = args.get("layer").and_then(|v| v.as_i64()).unwrap_or(1);+ if !(1..=16).contains(&mech) { return json!({"success": false, "errorCode": "bad_args", "error": "layer is a mechanical layer number, 1 to 16"}); }+ let num = |v: &Value, i: usize| v.get(i).and_then(|x| x.as_f64()).unwrap_or(0.0);+ let at = args.get("at").cloned().unwrap_or(json!([0, 0]));+ let rot = args.get("rotation").cloned().unwrap_or(json!([0, 0, 0]));+ if let Some(e) = crate::support::must_open(&board, 60) { return e; }+ let p = |v: f64| format!("{v}");+ let r = crate::agent::call("import_step", &[("path", step.clone()), ("x", p(num(&at, 0))), ("y", p(num(&at, 1))),+ ("rx", p(num(&rot, 0))), ("ry", p(num(&rot, 1))), ("rz", p(num(&rot, 2))), ("standoff", p(args.get("standoffMm").and_then(|v| v.as_f64()).unwrap_or(0.0))),+ ("side", side.clone()), ("layer", (56 + mech).to_string())], None, Duration::from_secs(120));+ let d = r.get("data").cloned().unwrap_or(Value::Null);+ if d["ok"] != json!(true) {+ return json!({"success": false, "errorCode": d.get("errorCode").cloned().unwrap_or(json!("import_failed")), "error": d.get("error").cloned().unwrap_or(r.get("error").cloned().unwrap_or(json!("the STEP was not placed"))), "reply": r});+ }+ let mm = |v: &Value| r3(f(v) / crate::routing::PER_MM);+ let bx = [mm(&d["box"][0]), mm(&d["box"][1]), mm(&d["box"][2]), mm(&d["box"][3])];+ let (standoff, height) = (mm(&d["standoff"]), mm(&d["height"]));+ // the parts' bodies it meets, from the same boxes height_check reads+ let bodies = crate::verbs::dispatch("bodies", &json!({}), &[]);+ let rows = bodies["bodies"].as_array().cloned().unwrap_or_default();+ let hits = meets(bx, (standoff, height.max(standoff)), &side, &rows);+ json!({"success": true, "mutated": true, "id": d["id"], "boxMm": bx, "standoffMm": standoff, "heightMm": height, "side": side, "layer": format!("Mechanical {mech}"),+ "meets": hits, "partsChecked": rows.len(),+ "_hint": "The STEP is a 3D body of the board (no part owns it), placed with its own origin at `at`. boxMm is its plan extent in the board model's frame; meets lists the parts' bodies it overlaps in plan and height. The board is not saved: altium_save keeps it, Edit > Undo takes it back. altium_render_board or altium_show_3d_board shows the fit."})+}++/// A format's exporter on Altium's File > Export menu: (label in its Save-as type, extension, index on Develop 26).+/// Measured 2026-10-30: the menu lists Ansoft Neutral .. PDF3D, and `PCB:Export Index=n` opens the n-th (1-based).+pub fn exporter(format: &str) -> Option<(&'static str, &'static str, u32)> {+ match format.to_ascii_lowercase().as_str() {+ "parasolid" | "x_t" | "xt" => Some(("PARASOLID", "x_t", 8)),+ "vrml" | "wrl" => Some(("VRML", "wrl", 16)),+ _ => None,+ }+}++/// An Altium dialog whose title holds `title`, within `secs`.+fn wait_dialog(title: &str, secs: u64) -> Option<i64> {+ let t0 = std::time::Instant::now();+ while t0.elapsed().as_secs() < secs {+ if let Some(h) = crate::dialogs::scan().iter().find(|d| d["title"].as_str().map(|t| t.contains(title)).unwrap_or(false)).and_then(|d| d["hwnd"].as_i64()) { return Some(h); }+ std::thread::sleep(Duration::from_millis(400));+ }+ None+}++/// Open exporter `index` through Altium's process launcher (outside the script engine: a RunProcess inside the agent+/// held it in the exporter's modal dialogs, and the next verb found it deaf, 2026-10-30) and answer its Export File+/// dialog when its Save-as type names `label`; cancel it otherwise. Answers the dialog and the launcher still running.+fn open_exporter(index: u32, label: &str) -> Result<(i64, std::process::Child), String> {+ let exe = crate::lifecycle::x2_exe_pub().ok_or("X2.exe not found")?;+ let mut child = crate::lifecycle::spawn_helper_pub(&exe, &format!("-RPCB:Export(Index={index})"))?;+ let Some(h) = wait_dialog("Export File", 15) else {+ crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(10));+ return Err(format!("exporter {index} opened no Export File dialog"));+ };+ // its Save-as type box names the format ("Export PARASOLID (*.x_t)"): reading the whole dialog's text walked the+ // file list and timed out (2026-10-30)+ let fc = crate::ab::call("desktop_find_controls", json!({"hwnd": h, "contains": "Save as type"}), &[], 15);+ let kind = fc["matches"].as_array().or(fc["output"]["matches"].as_array()).cloned().unwrap_or_default().iter()+ .filter_map(|m| m["value"].as_str().map(str::to_string)).collect::<Vec<_>>().join(" ").to_ascii_uppercase();+ if kind.contains(&label.to_ascii_uppercase()) { return Ok((h, child)); }+ crate::dialogs::press(h, "Cancel");+ crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(20));+ Err(format!("exporter {index} is not {label} ({kind})"))+}++/// altium_export_3d {filePath, format, output? | outputDir?}+pub fn export_3d(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let s = |k: &str| crate::support::s(args, k);+ let Some(board) = s("filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});+ };+ let format = s("format").unwrap_or_default().to_ascii_lowercase();+ let bpath = std::path::PathBuf::from(board.replace('\\', "/"));+ let stem = bpath.file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());+ if format == "step" || format == "stp" {+ // STEP is the standard's export_step; answered here too, so one call covers every 3D format+ let out = s("output").unwrap_or_else(|| bpath.parent().unwrap_or(std::path::Path::new(".")).join(format!("{stem}.step")).to_string_lossy().to_string());+ let mut r = crate::outputs::export_step(&json!({"filePath": board, "output": out}));+ r["format"] = json!("step");+ return r;+ }+ let Some((label, ext, known)) = exporter(&format) else {+ return json!({"success": false, "errorCode": "unsupported", "format": format,+ "error": format!("Altium writes no {format}: its 3D exporters are STEP, Parasolid and VRML (and 3D PDF, which the bridge cannot drive without a window yet)"),+ "formats": ["step", "parasolid", "vrml"], "_hint": "Ask for step, parasolid or vrml; a mesh format (stl, obj, glb, 3mf, ply) can be made from the STEP outside Altium."});+ };+ let out = s("output").unwrap_or_else(|| {+ let dir = s("outputDir").map(std::path::PathBuf::from).unwrap_or_else(|| bpath.parent().unwrap_or(std::path::Path::new(".")).to_path_buf());+ dir.join(format!("{stem}.{ext}")).to_string_lossy().to_string()+ }).replace('/', "\\");+ if let Some(e) = crate::support::must_open(&board, 60) { return e; }+ // a file already there would raise Windows' overwrite question: the caller asked for this path. Its folder must+ // exist: Windows' "Path does not exist" box stopped the save when the battery had just emptied it (2026-10-30)+ let _ = std::fs::remove_file(&out);+ if let Some(dir) = std::path::Path::new(&out.replace('\\', "/")).parent() { let _ = std::fs::create_dir_all(dir); }+ // the exporter runs outside the script engine: the agent stops for it and starts again after+ let stop = crate::lifecycle::stop();+ if stop.get("success").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "agent_stop_failed", "stop": stop}); }+ let r = run_exporter(&out, label, known, args);+ let start = crate::lifecycle::start(Duration::from_secs(90));+ let mut r = r;+ r["agentRestarted"] = json!(start.get("success").and_then(|v| v.as_bool()) == Some(true));+ if r.get("success").and_then(|b| b.as_bool()) == Some(true) { r["format"] = json!(format); }+ r+}++/// The exporter's dialogs, answered, and the file waited for. The agent is stopped while this runs.+fn run_exporter(out: &str, label: &str, known: u32, args: &Value) -> Value {+ // the exporter's place on the menu: the measured one first, then every other one, each checked by its file type+ let mut tried = Vec::new();+ let mut hwnd = None;+ for i in std::iter::once(known).chain((1..=20).filter(|i| *i != known)) {+ match open_exporter(i, label) { Ok((h, c)) => { hwnd = Some((i, h, c)); break; } Err(e) => tried.push(e) }+ // no dialog at all is Altium not ready (no board in front, the agent busy), not a menu in another order+ if tried.last().map(|t| t.contains("opened no")).unwrap_or(false) { break; }+ }+ let Some((index, h, mut child)) = hwnd else { return json!({"success": false, "errorCode": "exporter_not_found", "error": format!("no {label} exporter on Altium's File > Export menu"), "tried": tried}) };+ // the file name, read back: right after the dialog opens a set can be lost, and Save then saved nothing the+ // battery could see (Export Options never came, 2026-10-30)+ let norm = |v: &str| v.replace('\\', "/").to_ascii_lowercase();+ let mut named = false;+ for _ in 0..3 {+ crate::ab::call("desktop_ui_set", json!({"hwnd": h, "automationId": "1001", "text": out}), &[], 15);+ std::thread::sleep(Duration::from_millis(300));+ let back = crate::ab::call("desktop_find_controls", json!({"hwnd": h, "automationId": "1001"}), &[], 15);+ let vals: Vec<String> = back["matches"].as_array().or(back["output"]["matches"].as_array()).cloned().unwrap_or_default().iter().filter_map(|m| m["value"].as_str().map(norm)).collect();+ if vals.iter().any(|v| *v == norm(out)) { named = true; break; }+ }+ let give_up = |child: &mut std::process::Child, why: &str| -> Value {+ // never leave a dialog behind: it blocks every verb after this one+ // a Windows message over the dialog (Path does not exist ...) first, then the dialogs themselves+ for d in crate::dialogs::scan() {+ let btns: Vec<String> = d["buttons"].as_array().cloned().unwrap_or_default().iter().filter_map(|b| b.as_str().map(str::to_string)).collect();+ if d["title"].as_str() == Some("Export File") && btns.iter().any(|b| b == "OK") && !btns.iter().any(|b| b == "Cancel") { if let Some(x) = d["hwnd"].as_i64() { crate::dialogs::press(x, "OK"); } }+ }+ for d in crate::dialogs::scan() {+ let t = d["title"].as_str().unwrap_or("");+ if t.contains("Export File") || t.contains("Export Options") { if let Some(x) = d["hwnd"].as_i64() { crate::dialogs::press(x, "Cancel"); } }+ }+ crate::lifecycle::wait_helper_pub(child, Duration::from_secs(20));+ json!({"success": false, "errorCode": "dialog_failed", "error": why})+ };+ if !named { return give_up(&mut child, "the file name could not be set in Altium's Export File dialog"); }+ let mut options = None;+ for _ in 0..3 {+ crate::dialogs::press(h, "Save");+ options = wait_dialog("Export Options", 10);+ if options.is_some() { break; }+ }+ match options {+ Some(o) => { crate::dialogs::press(o, "OK"); }+ None => return give_up(&mut child, "Altium showed no Export Options after Save"),+ }+ // done when the file is there and has stopped growing+ let t0 = std::time::Instant::now();+ let mut last = 0u64;+ let mut size = 0u64;+ while t0.elapsed().as_secs() < crate::support::timeout_of(args, 300).as_secs() {+ std::thread::sleep(Duration::from_millis(800));+ size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);+ if size > 0 && size == last { break; }+ last = size;+ }+ // the export ends on Altium's Information box ("export complete"): it is ours, so answer it, or the agent cannot+ // start again behind it (agentRestarted false, 2026-10-30); then the launcher ends+ if let Some(i) = wait_dialog("Information", 15) { crate::dialogs::press(i, "OK"); }+ crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(60));+ if size == 0 { return json!({"success": false, "errorCode": "not_written", "error": format!("{out} was not written"), "dialogs": crate::dialogs::scan()}); }+ json!({"success": true, "path": out, "bytes": size, "exporter": label, "exporterIndex": index, "windowEtiquette": "background",+ "_hint": "Written by Altium's own exporter (File > Export) with its default options: the whole board, components with their 3D bodies, pad holes. The file is of the board as it is open in Altium."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn formats_altium_writes() {+ assert_eq!(exporter("Parasolid").map(|e| e.1), Some("x_t"));+ assert_eq!(exporter("wrl").map(|e| e.0), Some("VRML"));+ assert!(exporter("stl").is_none() && exporter("glb").is_none());+ }++ #[test]+ fn a_box_meets_the_bodies_it_overlaps() {+ let b = |r: &str, side: &str, x0: f64, x1: f64, z1: f64| json!({"ref": r, "side": side, "x0": x0, "x1": x1, "y0": 0.0, "y1": 10.0, "z0": 0.0, "z1": z1});+ let rows = vec![b("U1", "top", 0.0, 10.0, 2.0), b("J1", "top", 20.0, 30.0, 12.0), b("C9", "bottom", 0.0, 10.0, 1.0), b("", "top", 0.0, 50.0, 50.0)];+ // a lid 5 mm above the board, over U1 and J1: only the tall connector reaches it+ let hits = meets([0.0, 0.0, 40.0, 10.0], (5.0, 6.0), "top", &rows);+ assert_eq!(hits.len(), 1);+ assert_eq!(hits[0]["ref"], "J1");+ assert_eq!(hits[0]["overlapMm"], json!([10.0, 10.0, 1.0]));+ assert!(meets([0.0, 0.0, 40.0, 10.0], (0.0, 1.0), "bottom", &rows).iter().any(|h| h["ref"] == "C9"));+ }+}
bridge-rs/src/importdesign.rsadded+30@@ -0,0 +1,30 @@+//! import_design: a foreign design into a new native Altium project (EDA Bridge Standard #29, native). `kicad` goes+//! through Altium's KiCad importer (import_kicad). Every other format Altium's Import Wizard reads is refused by name+//! until the bridge drives it.+//!+//! EAGLE, mapped live on Altium Designer Develop 26.9 (2026-10-30), for the driver that comes next:+//! - ImporterManager:RunImporterManagerDialog opens "Import Wizard" (TImporterManagerForm). Its pages are panes named+//! Sheet_Start, Sheet_Importer; the buttons Back / Next / Finish / Cancel take UIA Invoke. Run it through the process+//! launcher (outside the script engine) and find it by window title: the dialog scan does not list it.+//! - Sheet_Importer is a grid (Grid_Importer) of importers. "EAGLE Projects and Designs" must be clicked with the mouse:+//! UIA Select does not reach the Delphi grid, and Next then imports the first row, 99SE DDB (which asks to close every+//! document: a Confirm the reaper answers No).+//! - Next hands over to "EAGLE Import Wizard" (TImporterWizardForm): "Importing EAGLE Design Files" (a list with Add /+//! Remove), then "Importing EAGLE Library Files" (.lbr), then pages not yet seen. Add opens "Load EAGLE Designs", an+//! old-style Open dialog: its file name box is automation id 1148 and only Enter takes it (the Open button's UIA+//! Invoke did nothing); a second Add right after the first refused SetValue.+use serde_json::{json, Value};++/// altium_import_design {format, filePath}+pub fn import_design(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let format = crate::support::s(args, "format").unwrap_or_default().to_ascii_lowercase();+ if crate::support::s(args, "filePath").is_none() { return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the design to import) is required"}); }+ match format.as_str() {+ "kicad" => { let mut r = crate::outputs::import_kicad(args); r["format"] = json!("kicad"); r }+ "" => json!({"success": false, "errorCode": "bad_args", "error": "format is required (kicad)"}),+ o => json!({"success": false, "errorCode": "unsupported", "format": o, "formats": ["kicad"],+ "error": format!("this bridge does not drive Altium's {o} importer yet"),+ "_hint": "Altium's Import Wizard reads EAGLE, PADS, OrCAD, P-CAD, Allegro, xDxDesigner, CADSTAR and Zuken designs: a person can run it from File > Import Wizard. EAGLE is the next one the bridge will drive."}),+ }+}
bridge-rs/src/main.rs+5−1@@ -36,6 +36,10 @@ mod liblint; mod pos; mod logtail; mod schbatch;+mod geom3d;+mod editpours;+mod toolupdate;+mod importdesign; mod impedance; mod inspect; mod lengths;@@ -73,7 +77,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.87";+pub const BRIDGE_VERSION: &str = "0.2.88"; fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> { let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/routing.rs+6−1@@ -645,6 +645,7 @@ pub fn shape_pours(d: &Value) -> Value { let mut by_layer = serde_json::Map::new(); let mut zones = Vec::new(); let mut unfilled = Vec::new();+ let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new(); for g in arr(d, "polys") { let layer = layer_name(i(&g[1])); let mut area = 0.0;@@ -665,7 +666,11 @@ pub fn shape_pours(d: &Value) -> Value { // a hatched pour is poured as tracks and arcs, not regions: its pieces say it is poured let pieces = g.get(6).and_then(|v| v.as_i64()).unwrap_or(0); let poured = area > 0.0 || pieces > 0;- let z = json!({"net": g[0], "name": g[5], "layer": layer, "layerId": g[1], "pourIndex": g[2], "outline": outline,+ // the standard's pour id: Altium's polygon name, made unique when two pours share one (edit_pours takes it)+ let base = g[5].as_str().unwrap_or("").to_string();+ let k = seen.entry(base.clone()).or_insert(0usize); *k += 1;+ let id = if *k == 1 { base.clone() } else { format!("{base}#{k}") };+ let z = json!({"id": id, "net": g[0], "name": g[5], "layer": layer, "layerId": g[1], "pourIndex": g[2], "outline": outline, "filledMm2": area, "islands": islands, "filled": poured, "hatchedPieces": pieces, "fills": fills}); if !poured { unfilled.push(z.clone());
bridge-rs/src/toolupdate.rsadded+72@@ -0,0 +1,72 @@+//! tool_update: Altium's own updates (EDA Bridge Standard #29, app tier). `check` gives every Altium on the machine+//! with its exact build; what Altium offers is shown on pages the bridge cannot read (Develop's Extensions & Updates page+//! lists extensions only, and none of its content is in the UI Automation tree, measured 2026-10-30), so `offered` is+//! null with the reason rather than a guess, and `apply` is refused by name. `auto` reads Altium's own update-check+//! settings from its preference files.+use serde_json::{json, Value};++/// X2.EXE's product version.+fn exe_version(exe: &str) -> Option<String> {+ let ps = format!("(Get-Item -LiteralPath '{}').VersionInfo.ProductVersion", exe.replace('\'', "''"));+ let o = std::process::Command::new("powershell").args(["-NoProfile", "-Command", &ps]).output().ok()?;+ let v = String::from_utf8_lossy(&o.stdout).trim().to_string();+ (!v.is_empty()).then_some(v)+}++/// The open documents with unsaved changes.+fn unsaved() -> Vec<String> {+ let d = crate::project::document_info(&json!({}));+ d["openDocuments"].as_array().cloned().unwrap_or_default().iter()+ .filter(|x| x["modified"] == json!(true)).filter_map(|x| x["path"].as_str().or(x["name"].as_str()).map(str::to_string)).collect()+}++/// altium_tool_update {action: check | apply | auto, enabled?}+pub fn tool_update(args: &Value) -> Value {+ let action = crate::support::s(args, "action").unwrap_or_else(|| "check".into()).to_ascii_lowercase();+ let installs: Vec<Value> = crate::support::detect_installs().into_iter().map(|mut i| {+ let v = i["exe"].as_str().and_then(exe_version);+ let folder = i["base_dir"].as_str().unwrap_or("").rsplit(['\\', '/']).next().unwrap_or("").to_string();+ i["edition"] = json!(if folder.to_ascii_lowercase().contains("develop") { "Altium Designer Develop" } else { "Altium Designer" });+ if i["major"] == json!("0") { if let Some(m) = v.as_deref().and_then(|v| v.split('.').next()) { i["major"] = json!(m); } }+ i["version"] = json!(v);+ i+ }).collect();+ if installs.is_empty() { return crate::support::not_installed(); }+ let running = crate::health::is_running();+ match action.as_str() {+ "check" => {+ // Altium Develop's Extensions page lists extensions only, no Altium build on offer, and none of its content+ // is in the UI Automation tree (measured 2026-10-30): the installed builds are read here, exactly, and what+ // is on offer is said to be unknown rather than guessed+ json!({"success": true, "installs": installs, "running": running, "checked": false, "offered": Value::Null,+ "why": "Altium shows its updates on pages the bridge cannot read: Develop's Extensions & Updates page lists extensions only, and its content is not exposed to UI Automation",+ "_hint": "installs gives each Altium on this machine with its exact build (from X2.EXE). Whether a newer build is offered is not readable from Altium yet: the user sees it in Altium (Extensions & Updates, or Altium's installer)."})+ }+ "apply" => {+ let open = if running { unsaved() } else { vec![] };+ json!({"success": false, "errorCode": "not_supported", "unsaved": open, "installs": installs,+ "error": "the bridge cannot apply an Altium update yet: Altium's update pages are not readable or drivable through UI Automation",+ "_hint": "The user updates Altium from inside it (Extensions & Updates) or with Altium's installer; save open work first (unsaved lists it)."})+ }+ "auto" => {+ // Altium's own update check lives in its preferences: read the keys that name it+ let la = std::env::var("APPDATA").unwrap_or_default();+ let mut found = Vec::new();+ for d in std::fs::read_dir(std::path::Path::new(&la).join("Altium")).into_iter().flatten().flatten() {+ for f in std::fs::read_dir(d.path()).into_iter().flatten().flatten() {+ let p = f.path();+ let Ok(t) = std::fs::read_to_string(&p) else { continue };+ for l in t.lines().filter(|l| { let x = l.to_ascii_lowercase(); x.contains("update") && x.contains('=') && (x.contains("check") || x.contains("auto")) }).take(10) {+ found.push(json!({"file": p.to_string_lossy(), "line": l.trim()}));+ }+ }+ }+ if args.get("enabled").is_some() {+ return json!({"success": false, "errorCode": "not_supported_yet", "settings": found,+ "error": "setting Altium's update check is not done yet: Altium rewrites its preferences on exit, so a change has to go through its Preferences dialog"});+ }+ json!({"success": true, "settings": found, "_hint": "Altium's update-check settings as its preference files hold them."})+ }+ o => json!({"success": false, "errorCode": "bad_args", "error": format!("action is check, apply or auto (got {o})")}),+ }+}
bridge-rs/src/verbs.rs+62−3@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[ "list_nets", "net_connections", "layers", "copper_layers", "read_rules", "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters", // the live-board lane AI Flow drives- "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+ "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "import_step", "edit_pours", "export_3d", "tool_update", "import_design", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen", // surfaces "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library", "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -350,7 +350,7 @@ fn describe() -> Value { &["schematic_data", "cross_check", "show_schematic", "activate_document"], &["The CURRENT sheet only: a hierarchical parent holds sheet symbols, not parts. Read each leaf sheet.", "Needs a .SchDoc current; 'no current schematic' -> altium_open_document / altium_show_schematic."], json!({})), verb_doc("cross_check", "Compare one schematic sheet's designators with a board's. Altium holds ONE current document, so the verb activates the board, reads it, then activates the sheet and reads that.",- json!({"board": "path to the .PcbDoc - optional, else the current board", "sheet": "path to the .SchDoc - optional, else the current sheet", "timeout": "seconds per step, default 45"}),+ json!({"board": "path to the .PcbDoc - optional, else the current board (with projectPath: the project's board)", "sheet": "path to the .SchDoc - optional, else the current sheet", "projectPath": "a .PrjPcb: every sheet it lists against its board instead of one sheet, through the standard's engine (parts kept out of the BOM by kind are not counted missing)", "timeout": "seconds per step, default 45"}), json!({"sheet": "string", "board": "path", "sameProject": "bool | null - same folder", "matched": "int", "onSheetNotOnBoard": "[designator]", "onBoardNotOnSheet": "[designator]", "schematicComponents": "int", "boardComponents": "int"}), 120, "Pass BOTH paths: with neither, one of the two reads has no current document and the call fails at stage board or sheet. Follow differences with altium_component_data / altium_schematic_data.", &["read_board", "read_schematic", "review_board"],@@ -447,6 +447,31 @@ fn describe() -> Value { json!({"footprints": "[{ref, footprint, library, status: up_to_date | differs | library_not_found, diff?: {padsAdded, padsRemoved, padsChanged: [{pad, changes}], bodies3d?}, why?}]", "differs": "int", "plan": "bool", "mutated": "bool", "replaced": "[{ref, replaced, netsKept, netsBefore}] (apply)", "problems": "[read-back problems] (apply)", "revision": "string"}), 600, "Plan first: each differing part's diff names the pads added, removed or changed (moved, resized, reshaped, redrilled, surface or through-hole) and a 3D body count that differs. apply:true replaces every differing part and reads them back: each must sit where it did and match its library. Save with altium_save.", &["edit_footprint", "footprint_from_land_pattern", "swap_footprint", "routing_drc", "save"], &["A pad new in the library has no net, and a removed pad's net goes with it: read padsAdded and padsRemoved before apply.", "Tracks are not moved to follow pads that moved: run altium_routing_drc after."], json!({"filePath": "C:/proj/Board.PcbDoc", "refs": ["U1"]})),+ verb_doc("edit_pours", "Change existing pours in place, without redrawing them: net, layer, hatching, minimum width, grid, dead copper, islands, necks, pouring over same-net objects and pour order; and clearance and thermals, which Altium keeps as design rules scoped to the polygon.",+ json!({"filePath": "the .PcbDoc (required)", "pours": "[{id (pour_state's) | name | net + layer?, set: {net?, layer?, hatch?: solid|45|90|none, minWidthMm?, gridMm?, removeDead?, removeIslands?, neckMm?, pourOverSameNet?, pourIndex?, clearanceMm?, connect?: direct|relief|none, reliefWidthMm?, reliefGapMm?, reliefEntries?: 2|4}}] (required)", "repour": "bool, default true", "expectedRevision": "string: refuse with stale_board if the board changed"}),+ json!({"edited": "[pour name]", "results": "[ok:<key> | err:<why>] per change, in order", "rulesWritten": "[{pour, rule, kind, gapMm, ok}] the clearance rules scoped to each pour", "before": "[{name, net, layer, pourIndex, filledMm2, islands}]", "after": "the same after the repour"}), 600,+ "Name pours as pour_state does. A net with no layer edits every pour on that net. Thermals (connect) are the pour's PolygonConnect rule, clearance a Clearance rule scoped IsNamedPolygon: both are Altium rules, named in the reply.",+ &["pour_state", "apply_pours", "remove_pours", "repour", "add_rule"], &["Clearance and thermals are rules: a broader rule of higher priority can still win; run_drc tells.", "The board is left unsaved: altium_save keeps it."], json!({"filePath": "C:/proj/Board.PcbDoc", "pours": [{"net": "GND", "layer": "B.Cu", "set": {"clearanceMm": 0.3, "connect": "relief", "reliefWidthMm": 0.3, "removeIslands": true}}]})),+ verb_doc("tool_update", "Altium's own updates. check gives every Altium on this machine with its exact build; whether a newer build is offered is not readable from Altium yet, so offered is null with the reason. auto reads Altium's own update-check settings. apply is refused by name until Altium's update pages can be driven.",+ json!({"action": "check | apply | auto, default check", "enabled": "bool (auto): refused for now - Altium rewrites its preferences on exit"}),+ json!({"installs": "[{edition, version, major, exe}]", "checked": "bool: whether an offer could be read (false today)", "offered": "the newer build on offer, or null", "why": "why offered is unknown", "unsaved": "[document] (apply)", "settings": "[{file, line}] (auto)"}), 60,+ "Read-only: nothing is opened or changed in Altium.",+ &["install", "readiness", "license_status"], &["Altium shows its updates on pages the bridge cannot read: the user updates Altium from inside it or with Altium's installer."], json!({"action": "check"})),+ verb_doc("import_design", "Bring a foreign design into a new Altium project: kicad through Altium's KiCad importer. A format the bridge does not drive yet (EAGLE, PADS, OrCAD and the rest of Altium's Import Wizard) is refused by name.",+ json!({"format": "kicad (required; eagle and the others are refused by name for now)", "filePath": "the design (required)", "timeout": "seconds, default 300"}),+ json!({"format": "string", "result": "import_kicad's answer"}), 600,+ "kicad answers as import_kicad. EAGLE is mapped and comes next; until then a person runs File > Import Wizard.",+ &["import_kicad", "open_project", "project_info"], &["Altium's Import Wizard reads many formats; the bridge drives only KiCad's importer so far."], json!({"format": "kicad", "filePath": "C:/designs/board.kicad_pcb"})),+ verb_doc("export_3d", "The board's 3D model in another format than STEP, by Altium's own exporter (File > Export): Parasolid (.x_t) or VRML (.wrl). step answers through export_step; a format Altium does not write is refused by name.",+ json!({"filePath": "the .PcbDoc (required)", "format": "parasolid | vrml | step (required; stl, obj, glb, 3mf, iges, ply and pdf3d are refused by name)", "output": "the file to write (default beside the board)", "outputDir": "folder, when output is not given", "timeout": "seconds to wait for the file, default 300"}),+ json!({"path": "the file", "bytes": "int", "format": "string", "exporter": "Altium's exporter", "exporterIndex": "its place on File > Export"}), 360,+ "Altium's exporters ask in dialogs: the bridge answers them (file name, then the export options at their defaults: the whole board, every component with its 3D body, pad holes) and waits for the file.",+ &["export_step", "render_board", "import_step", "bodies"], &["Altium's own defaults: folded boards export folded; components export as their 3D bodies.", "A mesh format (stl, obj, glb) is not Altium's: make it from the STEP outside Altium."], json!({"filePath": "C:/proj/Board.PcbDoc", "format": "parasolid"})),+ verb_doc("import_step", "Place a STEP with the board as free 3D geometry (an enclosure, a bracket, a lid) for fit checks: a 3D body of the board itself on a mechanical layer, belonging to no part, and the parts' bodies it now meets.",+ json!({"filePath": "the .PcbDoc (required)", "stepPath": "the .step or .stp on this machine (required)", "at": "[x, y] mm in the board model's frame (routing_state): where the STEP's own origin lands, default [0, 0]", "rotation": "[rx, ry, rz] degrees, default [0, 0, 0]", "standoffMm": "height of the model's origin above the board surface, default 0", "side": "top | bottom, default top", "layer": "mechanical layer 1 to 16, default 1"}),+ json!({"boxMm": "[x0, y0, x1, y1] its plan extent", "standoffMm": "float", "heightMm": "its top above the board surface", "meets": "[{ref, overlapMm: [x, y, z]}] the parts' bodies it overlaps in plan and height", "partsChecked": "int", "id": "the body's handle"}), 180,+ "add_body puts a model on one footprint; this one belongs to the board. The board is left unsaved (altium_save keeps it).",+ &["add_body", "bodies", "height_check", "render_board", "show_3d_board"], &["meets compares boxes: a hollow enclosure's box holds the whole board, so read it with height_check's clearance or look in 3D.", "Altium places the STEP by its own origin: a model drawn far from its origin lands far away (boxMm shows where)."], json!({"filePath": "C:/proj/Board.PcbDoc", "stepPath": "C:/mech/Lid.step", "at": [0, 0], "standoffMm": 8})), verb_doc("sch_batch", "Apply a list of schematic edits to one sheet in order, all or nothing: each op is a schematic verb with its own arguments, seeing the sheet as the earlier ops left it. When one fails, Altium's Undo takes back the ops already applied and the sheet is checked back to where it was.", json!({"filePath": "the .SchDoc (required; sheet accepted)", "ops": "[{op: sch_place_part | sch_connect_pins | sch_connect | sch_edit | sch_edit_label | sch_junction | sch_bus | sch_bus_entry | sch_connect_to_bus | sch_text | sch_delete_wire | sch_split_wire | sch_move_region | sch_reset_fields | sch_update_from_library | sch_swap_part | sch_fix_connectivity | annotate, ...that verb's arguments}] (required)", "dryRun": "bool: check every op and answer the plan, change nothing", "erc": "bool, default true: compile before and after for ercBefore / ercAfter (false skips both)", "projectPath": "the .PrjPcb (default the project beside the sheet that lists it)"}), json!({"results": "[{op, output}] in order", "failedOp": "the index of the op that failed", "restored": "bool: the sheet is as it was before the batch", "ercBefore": "{class: n} the sheet's Messages before", "ercAfter": "and after", "mutated": "bool", "undoSteps": "int"}), 900,@@ -1022,7 +1047,7 @@ fn describe() -> Value { &["One layer per call; split a pair that changes layer into two calls at the via pair.", "The waypoints are the pair's centreline, so keep them clear of other copper by half the pair's width."], json!({"pos": "USB_DP", "neg": "USB_DN", "from": {"pos": "U1.14", "neg": "U1.15"}, "to": {"pos": "J1.3", "neg": "J1.2"}, "via": [[20, 10], [30, 10]], "diffOhms": 90})), verb_doc("schematic_review", "Review the schematic before Update PCB: every placed pin (read from the sheet files, with its electrical type) against Altium's compiled netlist. Errors: power pins on no net, outputs driving each other. Warnings: pins on no net, one-pin nets, inputs nothing drives, IC supplies with no decoupling capacitor to ground.",- json!({"projectPath": "the .PrjPcb (its sheets are read from file; the netlist is Altium's compile)"}),+ json!({"drawing": "bool, default true: read each sheet's drawing too, for the drawing checks (dangling wire ends, labels off their wire, overlapping symbols)", "projectPath": "the .PrjPcb (its sheets are read from file; the netlist is Altium's compile)"}), json!({"ok": "bool - no errors", "errors": "[{check, pin|net, ...}]", "warnings": "[{check, ...}]", "decoupling": "[{net, ics, capacitors, ok}]", "pins": "int", "nets": "int", "sheets": "[path]"}), 300, "Fix on the sheets (altium_sch_connect, altium_sch_place_part for a missing capacitor), then altium_update_pcb. altium_run_erc is Altium's own ERC with its rules.", &["netlist", "read_sheet_file", "run_erc", "sch_connect", "update_pcb"],@@ -2226,6 +2251,11 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "render_board" => crate::render::render_board(args), "log_tail" => crate::logtail::log_tail(args), "sch_batch" => crate::schbatch::sch_batch(args),+ "import_step" => crate::geom3d::import_step(args),+ "edit_pours" => crate::editpours::edit_pours(args),+ "export_3d" => crate::geom3d::export_3d(args),+ "tool_update" => crate::toolupdate::tool_update(args),+ "import_design" => crate::importdesign::import_design(args), "symbol_mode" => library::symbol_mode(args), "cleanup_libs" => library::cleanup_libs(args), "install_library" => library::install_library(args),@@ -2294,8 +2324,37 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> /// Compare a schematic sheet against a board. Altium CANNOT hold both current at once — /// `GetCurrentPCBBoard` follows the focused document — so this reads them in TURN: activate the /// board, read it, activate the sheet, read it.+/// altium_cross_check {projectPath, board?}: every sheet the project lists against its board.+fn cross_check_project(prj: &str, args: &Value) -> Value {+ let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+ if text.is_empty() { return json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")}); }+ let dir = std::path::Path::new(prj).parent().map(|p| p.to_path_buf()).unwrap_or_default();+ let project = crate::bom::parse_project(&text, &dir);+ let Some(board) = s(args, "board").or_else(|| s(args, "pcbPath")).or_else(|| project.boards.first().cloned()) else {+ return json!({"success": false, "errorCode": "no_board", "error": "the project lists no .PcbDoc: pass board"});+ };+ let mut parts = Vec::new();+ let mut unread = Vec::new();+ for sh in &project.sheets {+ let r = crate::schdoc::read_sheet_file(&json!({"path": sh, "params": true}));+ match r["components"].as_array() { Some(a) => parts.extend(a.iter().cloned()), None => unread.push(json!({"sheet": sh, "error": r.get("error").cloned().unwrap_or(Value::Null)})) }+ }+ if let Some(e) = support::must_open(&board, 60) { return e; }+ let st = crate::routing::routing_state(&json!({}));+ if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }+ let mut out = adom_eda_checks::bom::cross_check(&json!({"sheetParts": parts, "board": st}));+ out["project"] = json!(prj);+ out["board"] = json!(board);+ out["sheets"] = json!(project.sheets);+ out["unreadSheets"] = json!(unread);+ out+}+ fn cross_check(args: &Value) -> Value { if let Some(g) = need_licensed() { return g; }+ // the whole project: every sheet's parts against the board, by the standard's engine (adom-eda-checks cross_check),+ // parts kept out of the BOM by their kind not counted as missing from the board+ if let Some(prj) = s(args, "projectPath") { return cross_check_project(&prj, args); } let timeout = Duration::from_secs_f64(support::f_or(args, "timeout", 45.0)); let read = |kind: &str, path: Option<String>| -> Result<Value, Value> { if let Some(p) = &path {
bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-eda-checks"-version = "0.23.0"+version = "0.24.0" edition = "2021" description = "The EDA Bridge Standard's checks and board-file writers, computed from the board model JSON: no bridge calls, no tool." license = "MIT"
bridge-rs/vendor/adom-eda-checks/README.md+2@@ -14,6 +14,7 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives. | `assembly_check` | board, stack? | the board against JLCPCB's two PCBA tiers as published (with the page and its read date): size (or `panelMm`), thickness and layers from the stack, one or two sides, the smallest two-pad part and the finest IC pitch, fiducials, and parts without an LCSC number (`lcscMissing` from the bridge's BOM). Pads sharing one centre are one land, and a component with no pads is no part. `service` is the cheaper tier every rule allows. Matches the Altium bridge's answers on its test boards. From its assembly.rs | | `auto_classes` | board | net classes from the names the nets already have (GND, Power, Clock, HighSpeed) and differential pairs from their suffixes (`_P`/`_N`, `DP`/`DN`, `+`/`-`), with `applyArgs`: the net_classes and diff_pairs calls that write them (Power with a `powerWidthMm` width rule). From the Altium bridge's autoclass.rs | | `board_report` | board, and every companion it can use | every check the engine has, run on this bundle, as one self-contained HTML page (`text`), dark by default: fab limits (with `fab`), JLCPCB assembly, schematic review and symbols against footprints (with `sheetParts` and `netlist`), impedance, return paths and copper balance (with `stack`), 3D heights (with `bodies`), the design review, and the tool's own DRC (`drc`) and a base64 PNG of the board (`picture`) when the bridge passes them; `args` carries `lcscMissing`, `panelMm`, `gridMm` and `alwaysChecked` to those checks. A section whose input is missing says which to pass. From the Altium bridge's report.rs |+| `bom` | sheetParts, board? | the bill of materials: fitted parts grouped one line per manufacturer part number (natural designator order), a variant applied (`args.variant`: notFitted, alternates), checks for what an order needs (missing MPN, maker or Mouser/DigiKey/LCSC numbers, lines mixing values, JLCPCB lines without LCSC, DNP, excluded and not-purchased parts, sheet and board mismatches), and the order files as text (`files[]`: bom.csv, bom-jlcpcb.csv, cpl-jlcpcb.csv, bom-mouser.csv, bom-digikey.csv); from the Altium bridge's bom.rs | | `check_clearance` | board, bodies? | pairs of parts closer than `thresholdMm`, closest first: `mode: courtyard` (default 0.25) measures part boxes (pads, and 3D bodies when given) on the same side; `mode: pads` (default 0.2) measures pad copper of different parts that shares a layer, by its real outline, skipping same-net pairs unless `includeSameNet`; `refs` keeps pairs involving those parts. A part under a raised one (pads apart, bodies apart in 3D) is listed in `stacked`, not `pairs`, as placement_check lists it. From the KiCad bridge's place_tools | | `check_orientation` | board | advisory: each two-pad part's quarter turns scored by airline length (MST of a routable net with the pad there, distance to the nearest pad of a plane-like net such as GND); turns saving `minImprovementMm` (0.6) or more are suggested, nothing moves. From the Altium bridge's design.rs | | `copper_balance` | board, stack, pours | copper per layer and how evenly mirrored layers match (bow and twist) |@@ -22,6 +23,7 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives. | `find_space` | board, bodies? | free spots for a part (`part`, or `sizeMm`) near another (`near`) or a point (`at`): clear of other part boxes on that side by `clearanceMm`, of that side's routed tracks and the vias, `edgeMm` inside the outline (arcs sampled), nearest first, as where the part's origin goes; `check: true` lists parts that overlap (and, with bodies, those `stacked` under a raised one) or have pads off the outline, as placement_check judges them. Pours do not block (they re-pour). From the Altium bridge's design.rs | | `fab_check` | board, stack?, rules?, silk?, fab? | the board's smallest features, compared with a fab's limits from adom/pcb-design-rules; each finding names the fab's page and the date it was read | | `impedance` | stack | the track width (and pair gap) for a target impedance on each copper layer; `apply` answers `add_rule` arguments |+| `cross_check` | sheetParts, board | the sheets' designators against the board's: matched, on the sheets but not the board, on the board but on no sheet | | `current_capacity` | board, stack? | per net and layer, the narrowest copper against the width the current needs (IPC-2221), and the vias a layer change needs | | `footprint_from_land_pattern` | args only | a footprint laid out from a datasheet's recommended land pattern (`family` chip, dual, sot, quad or bga, with pitch, span, pad size, `exposedPad`, `body`): pads numbered the standard way (pin 1 top-left, counterclockwise; BGA rows without I, O, Q, S, X, Z), a shorter column spread over the longer one's span (SOT-23-5's pins 4 and 5 level with 3 and 1), silkscreen (`overlay`) kept `silkClearance` from copper with a pin-1 dot, a `fab` outline with a pin-1 chamfer and the `courtyard` round the pads and body grown by its margin, in mm, Y up, origin at the centre. A missing number is refused by name. Each bridge writes it in its own library format. From the Altium bridge's footprint.rs | | `height_check` | bodies, board? | each part's height on its side, parts over `maxTopMm`/`maxBottomMm` or under a lid region (`regions`), body collisions and near misses (`minGapMm`); `noBody` and `complete: false` when a part has no 3D body |
bridge-rs/vendor/adom-eda-checks/src/bom.rsadded+294@@ -0,0 +1,294 @@+//! The bill of materials, from the sheets' parts and the board: fitted parts grouped one line per manufacturer part+//! number, checked for what an order needs, and the order files as text (generic, JLCPCB BOM + CPL, Mouser and DigiKey+//! uploads). Ported from the Altium bridge's bom.rs so every bridge answers `bom` the same way; the bridge reads the+//! parts and writes the files. Also `cross_check`: the sheets' designators against the board's.+use serde_json::{json, Map, Value};+use std::collections::{BTreeMap, BTreeSet};++/// Parameter names that mean the same thing across libraries and tools (Altium templates, the Adom part import, the+/// wiki's Cloud Library, Altium 365 supplier links, KiCad fields, EAGLE attributes).+const MPN: &[&str] = &["MPN", "Manufacturer Part Number", "Manufacturer Part Number 1", "Mfr Part #", "Mfr. Part Number", "MFR PN", "MFR_PN", "MANUFACTURER_PART_NUMBER", "MANUFACTURER_PN", "Part Number", "PartNumber", "Part_Number"];+const MFR: &[&str] = &["Manufacturer", "Manufacturer 1", "Manufacturer Name", "Mfr", "MANUFACTURER", "MANUFACTURER_NAME"];+const MOUSER: &[&str] = &["Mouser Part #", "Mouser Part Number", "Mouser PN", "MOUSER_PN", "Mouser"];+const DIGIKEY: &[&str] = &["DigiKey Part #", "Digi-Key Part Number", "DigiKey Part Number", "Digikey PN", "DIGIKEY_PN", "DigiKey", "Digi-Key_PN"];+const LCSC: &[&str] = &["LCSC Part #", "LCSC", "LCSC Part", "LCSC_PN", "JLCPCB Part #", "JLC Part #", "JLCPCB"];+const VALUE: &[&str] = &["Value", "VALUE"];+const PACKAGE: &[&str] = &["Package", "Case/Package", "PACKAGE"];+const DNP: &[&str] = &["DNP", "Do Not Populate", "DNF", "Do Not Fit"];+const DESCRIPTION: &[&str] = &["Description", "DESCRIPTION"];+const FIELDS: &[(&str, &[&str])] = &[("mpn", MPN), ("manufacturer", MFR), ("mouser", MOUSER), ("digikey", DIGIKEY), ("lcsc", LCSC)];++fn st(v: &Value) -> String { match v { Value::String(s) => s.clone(), Value::Null => String::new(), o => o.to_string() } }++/// R1 < R2 < R10 < R10A: the letters, then the number, then the rest.+pub fn natural_key(d: &str) -> (String, u64, String) {+ let pre: String = d.chars().take_while(|c| !c.is_ascii_digit()).collect();+ let rest = &d[pre.len()..];+ let num: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();+ (pre.to_ascii_uppercase(), num.parse().unwrap_or(0), rest[num.len()..].to_string())+}++fn truthy(v: &str) -> bool { matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "y" | "dnp" | "x") }++/// One part, merged from its sheet (parameters) and the board (footprint, placement).+#[derive(Debug, Clone, Default)]+pub struct Part {+ pub designator: String,+ pub comment: String,+ pub description: String,+ pub lib_ref: String,+ /// out of the BOM by its kind (Altium's graphical, net tie and standard-no-BOM kinds; KiCad's exclude from BOM)+ pub no_bom: bool,+ pub params: Vec<(String, String)>,+ pub footprint: String,+ pub placed: Option<(f64, f64, f64, String)>,+ pub dnp: bool,+ pub alternate: String,+ pub managed: bool,+ pub source_lib: String,+}++impl Part {+ fn get(&self, names: &[&str]) -> String {+ for n in names {+ if let Some((_, v)) = self.params.iter().find(|(k, v)| k.eq_ignore_ascii_case(n) && !v.trim().is_empty() && !v.trim().starts_with('=')) { return v.trim().to_string(); }+ }+ String::new()+ }+ fn mpn(&self) -> String { self.get(MPN) }+ fn value(&self) -> String { let v = self.get(VALUE); if v.is_empty() { self.comment.clone() } else { v } }+ /// Copper test pads, fiducials and the like carry an MPN or maker that says nothing is bought ("none (PCB copper)"):+ /// they stay in the BOM, marked, and out of the ordering and assembly files.+ fn not_purchased(&self) -> bool {+ [self.mpn(), self.get(MFR)].iter().any(|v| {+ let m = v.trim().to_ascii_lowercase();+ m.starts_with("none") || m == "n/a" || m == "na" || m == "-" || m.contains("pcb copper") || m.contains("not purchased") || m.contains("no part")+ })+ }+}++/// The parts from the sheetParts companion (units of one part merged by designator), with the board's footprint and+/// placement. Returns (parts, designators on the board but on no sheet).+pub fn parts(sheet: &[Value], board: Option<&Value>) -> (Vec<Part>, Vec<String>) {+ let mut by: BTreeMap<String, Part> = BTreeMap::new();+ for c in sheet {+ let d = st(&c["designator"]);+ if d.is_empty() || d.ends_with('?') { continue; }+ // params: [{name, value}] or {name: value}+ let params: Vec<(String, String)> = match &c["params"] {+ Value::Array(a) => a.iter().filter(|p| p.get("value").is_some()).map(|p| (st(&p["name"]), st(&p["value"]))).collect(),+ Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), st(v))).collect(),+ _ => Vec::new(),+ };+ let kind = c["kind"].as_i64().unwrap_or(0);+ let no_bom = matches!(kind, 2 | 4 | 5) || c["inBom"] == false || c["excludeFromBom"] == true;+ let e = by.entry(d.to_ascii_uppercase()).or_insert_with(|| Part {+ designator: d.clone(), comment: [&c["comment"], &c["value"]].iter().map(|v| st(v)).find(|s| !s.is_empty()).unwrap_or_default(),+ description: st(&c["description"]), lib_ref: [&c["libRef"], &c["libReference"], &c["libId"]].iter().map(|v| st(v)).find(|s| !s.is_empty()).unwrap_or_default(),+ no_bom, managed: !st(&c["itemGuid"]).is_empty(), source_lib: st(&c["sourceLibrary"]), dnp: c["dnp"] == true, ..Default::default() });+ // a multi-unit part appears once per unit: keep the first, add what it lacks+ for (k, v) in params { if !e.params.iter().any(|(k2, _)| k2.eq_ignore_ascii_case(&k)) { e.params.push((k, v)); } }+ if c["dnp"] == true { e.dnp = true; }+ if e.footprint.is_empty() { e.footprint = [&c["footprint"], &c["pattern"]].iter().map(|v| st(v)).find(|s| !s.is_empty()).unwrap_or_default(); }+ }+ let mut board_only = Vec::new();+ if let Some(b) = board {+ for c in b["components"].as_array().cloned().unwrap_or_default() {+ let d = st(&c["ref"]);+ if d.is_empty() { continue; }+ let placed = Some((c["x"].as_f64().unwrap_or(0.0), c["y"].as_f64().unwrap_or(0.0), c["rotation"].as_f64().unwrap_or(0.0), if c["side"] == "bottom" { "bottom".to_string() } else { "top".to_string() }));+ match by.get_mut(&d.to_ascii_uppercase()) {+ Some(p) => { let pat = st(&c["pattern"]); if !pat.is_empty() { p.footprint = pat; } p.placed = placed; }+ None => board_only.push(d),+ }+ }+ }+ for p in by.values_mut() {+ if truthy(&p.get(DNP)) || p.get(&["Fitted"]).eq_ignore_ascii_case("false") { p.dnp = true; }+ }+ board_only.sort_by_key(|d| natural_key(d));+ (by.into_values().collect(), board_only)+}++/// Group the fitted parts: one line per manufacturer part number, else per value + footprint. Returns (lines, checks).+pub fn group(parts: &[Part]) -> (Vec<Value>, Value) {+ let mut groups: BTreeMap<String, Vec<&Part>> = BTreeMap::new();+ for p in parts.iter().filter(|p| !p.dnp && !p.no_bom) {+ let m = p.mpn();+ let key = if m.is_empty() { format!("~{}|{}", p.value().to_ascii_uppercase(), p.footprint.to_ascii_uppercase()) } else { format!("{}|{}", m.to_ascii_uppercase(), p.get(MFR).to_ascii_uppercase()) };+ groups.entry(key).or_default().push(p);+ }+ let mut lines = Vec::new();+ let mut inconsistent = Vec::new();+ for (_, mut g) in groups {+ g.sort_by_key(|p| natural_key(&p.designator));+ let refs: Vec<String> = g.iter().map(|p| p.designator.clone()).collect();+ let mut line = Map::new();+ line.insert("quantity".into(), json!(g.len()));+ line.insert("designators".into(), json!(refs));+ for (name, names) in FIELDS {+ let mut distinct: Vec<String> = g.iter().map(|p| p.get(names)).filter(|v| !v.is_empty()).collect();+ distinct.sort(); distinct.dedup();+ if distinct.len() > 1 { inconsistent.push(json!({"field": name, "designators": refs, "values": distinct})); }+ line.insert((*name).into(), json!(distinct.first().cloned().unwrap_or_default()));+ }+ let first = g[0];+ let mut fps: Vec<&str> = g.iter().map(|p| p.footprint.as_str()).filter(|f| !f.is_empty()).collect();+ fps.sort(); fps.dedup();+ if fps.len() > 1 { inconsistent.push(json!({"field": "footprint", "designators": refs, "values": fps})); }+ line.insert("value".into(), json!(first.value()));+ line.insert("comment".into(), json!(first.comment));+ line.insert("description".into(), json!(if first.description.is_empty() { first.get(DESCRIPTION) } else { first.description.clone() }));+ line.insert("sourceLibrary".into(), json!(first.source_lib));+ line.insert("managed".into(), json!(first.managed));+ line.insert("footprint".into(), json!(fps.first().copied().unwrap_or("")));+ line.insert("package".into(), json!(first.get(PACKAGE)));+ line.insert("libReference".into(), json!(first.lib_ref));+ line.insert("purchase".into(), json!(!first.not_purchased()));+ lines.push(Value::Object(line));+ }+ lines.sort_by_key(|l| natural_key(l["designators"][0].as_str().unwrap_or("")));+ let sorted = |mut v: Vec<String>| { v.sort_by_key(|d| natural_key(d)); v };+ let fitted: Vec<&Part> = parts.iter().filter(|p| !p.dnp && !p.no_bom && !p.not_purchased()).collect();+ let missing = |names: &[&str]| sorted(fitted.iter().filter(|p| p.get(names).is_empty()).map(|p| p.designator.clone()).collect());+ let no_lcsc: Vec<Value> = lines.iter().filter(|l| l["purchase"] == json!(true) && st(&l["lcsc"]).is_empty())+ .map(|l| json!({"designators": l["designators"], "mpn": l["mpn"], "value": l["value"]})).collect();+ let checks = json!({+ "missingMpn": missing(MPN), "missingManufacturer": missing(MFR),+ "missingPartNumbers": {"mouser": missing(MOUSER), "digikey": missing(DIGIKEY), "lcsc": missing(LCSC)},+ "inconsistent": inconsistent,+ "dnp": sorted(parts.iter().filter(|p| p.dnp).map(|p| p.designator.clone()).collect()),+ "excludedKinds": sorted(parts.iter().filter(|p| !p.dnp && p.no_bom).map(|p| p.designator.clone()).collect()),+ "notPurchased": sorted(parts.iter().filter(|p| !p.dnp && !p.no_bom && p.not_purchased()).map(|p| p.designator.clone()).collect()),+ "jlcpcb": {"ready": no_lcsc.is_empty(), "linesWithoutLcsc": no_lcsc},+ });+ (lines, checks)+}++fn csv(rows: &[Vec<String>]) -> String {+ let cell = |s: &str| if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() };+ rows.iter().map(|r| r.iter().map(|c| cell(c)).collect::<Vec<_>>().join(",")).collect::<Vec<_>>().join("\r\n") + "\r\n"+}++/// The order files as (name, text). `boards` multiplies the quantities of the distributor uploads.+pub fn files(lines: &[Value], parts: &[Part], boards: u64) -> Vec<(String, String)> {+ let refs = |l: &Value| l["designators"].as_array().map(|a| a.iter().map(st).collect::<Vec<_>>().join(",")).unwrap_or_default();+ let mut out = Vec::new();+ let mut rows = vec![["Line", "Quantity", "Designators", "Value", "Comment", "Description", "Footprint", "Package", "MPN", "Manufacturer", "Mouser Part #", "DigiKey Part #", "LCSC Part #"].map(String::from).to_vec()];+ for (i, l) in lines.iter().enumerate() {+ rows.push(vec![(i + 1).to_string(), st(&l["quantity"]), refs(l), st(&l["value"]), st(&l["comment"]), st(&l["description"]), st(&l["footprint"]), st(&l["package"]), st(&l["mpn"]), st(&l["manufacturer"]), st(&l["mouser"]), st(&l["digikey"]), st(&l["lcsc"])]);+ }+ out.push(("bom.csv".to_string(), csv(&rows)));+ // JLCPCB assembly: their BOM and CPL columns, mm, Top/Bottom+ let mut j = vec![["Comment", "Designator", "Footprint", "LCSC Part #"].map(String::from).to_vec()];+ for l in lines.iter().filter(|l| l["purchase"] != json!(false)) { j.push(vec![st(&l["value"]), refs(l), st(&l["footprint"]), st(&l["lcsc"])]); }+ out.push(("bom-jlcpcb.csv".to_string(), csv(&j)));+ let mut c = vec![["Designator", "Mid X", "Mid Y", "Layer", "Rotation"].map(String::from).to_vec()];+ let mut placed: Vec<&Part> = parts.iter().filter(|p| !p.dnp && !p.no_bom && !p.not_purchased() && p.placed.is_some()).collect();+ placed.sort_by_key(|p| natural_key(&p.designator));+ for p in placed {+ let (x, y, r, side) = p.placed.clone().unwrap();+ c.push(vec![p.designator.clone(), format!("{x:.4}mm"), format!("{y:.4}mm"), if side == "bottom" { "Bottom".into() } else { "Top".into() }, format!("{}", (r.rem_euclid(360.0) * 1000.0).round() / 1000.0)]);+ }+ out.push(("cpl-jlcpcb.csv".to_string(), csv(&c)));+ // the distributors' BOM tools (Mouser BOM Tool, DigiKey myLists) map these headers directly+ for (name, field, header) in [("bom-mouser.csv", "mouser", "Mouser Part Number"), ("bom-digikey.csv", "digikey", "Digi-Key Part Number")] {+ let mut m = vec![vec![header.to_string(), "Manufacturer Part Number".into(), "Manufacturer".into(), "Quantity".into(), "Customer Reference".into()]];+ for l in lines.iter().filter(|l| l["purchase"] != json!(false) && (!st(&l[field]).is_empty() || !st(&l["mpn"]).is_empty())) {+ m.push(vec![st(&l[field]), st(&l["mpn"]), st(&l["manufacturer"]), (l["quantity"].as_u64().unwrap_or(0) * boards.max(1)).to_string(), refs(l)]);+ }+ out.push((name.to_string(), csv(&m)));+ }+ out+}++fn sheet_list(input: &Value) -> Option<Vec<Value>> {+ let p = crate::input::part(input, "sheetParts")?;+ p.get("components").or(Some(&p)).and_then(|x| x.as_array()).cloned()+}++/// bom: input {sheetParts, board?, args: {variant? (the standard `variants` row: {name, notFitted: [ref], alternates:+/// [{designator, part | fields}]}), boards? (1)}}. Parts carry designator, comment or value, description, libRef,+/// footprint?, kind? (Altium) or inBom/excludeFromBom (KiCad), dnp?, params ([{name, value}] or {name: value}).+pub fn bom(input: &Value) -> Value {+ let Some(sheet) = sheet_list(input) else { return crate::input::refuse("bad_args", "pass the sheets' parts (every sheet, with their parameters) as sheetParts") };+ let board = crate::input::part(input, "board");+ let (mut list, board_only) = parts(&sheet, board.as_ref());+ let args = &input["args"];+ let variant = &args["variant"];+ let mut alternates = Vec::new();+ if variant.is_object() {+ let nf: BTreeSet<String> = variant["notFitted"].as_array().map(|a| a.iter().map(|x| st(x).to_ascii_uppercase()).collect()).unwrap_or_default();+ let alts: BTreeMap<String, String> = match &variant["alternates"] {+ Value::Array(a) => a.iter().map(|x| (st(&x["designator"]).to_ascii_uppercase(), if x["part"].is_null() { st(&x["fields"]) } else { st(&x["part"]) })).collect(),+ Value::Object(o) => o.iter().map(|(k, v)| (k.to_ascii_uppercase(), st(v))).collect(),+ _ => BTreeMap::new(),+ };+ for p in list.iter_mut() {+ let k = p.designator.to_ascii_uppercase();+ if nf.contains(&k) { p.dnp = true; }+ if let Some(a) = alts.get(&k) { p.alternate = a.clone(); alternates.push(json!({"designator": p.designator, "alternatePart": a})); }+ }+ }+ let (lines, mut checks) = group(&list);+ let mut not_on_board: Vec<String> = if board.is_some() { list.iter().filter(|p| p.placed.is_none() && !p.no_bom).map(|p| p.designator.clone()).collect() } else { Vec::new() };+ not_on_board.sort_by_key(|d| natural_key(d));+ checks["sheetNotOnBoard"] = json!(not_on_board);+ checks["boardNotOnSheet"] = json!(board_only);+ let boards = args["boards"].as_u64().unwrap_or(1);+ let fitted = list.iter().filter(|p| !p.dnp && !p.no_bom).count();+ let files: Vec<Value> = files(&lines, &list, boards).into_iter().map(|(n, t)| json!({"name": n, "text": t})).collect();+ json!({"success": true, "variant": variant["name"], "lines": lines, "lineCount": lines.len(), "fittedParts": fitted, "checks": checks, "alternates": alternates, "boards": boards, "files": files,+ "_hint": "One line per manufacturer part number. Write files[] (bom.csv, bom-jlcpcb.csv + cpl-jlcpcb.csv for JLCPCB assembly, bom-mouser.csv and bom-digikey.csv for those sites' BOM tools). checks: parts with no MPN or distributor number (find them with adom-parts-search and write them back with sheet_params), lines that mix values for one part number (checks.inconsistent), JLCPCB lines with no LCSC number, and parts on the sheets but not the board or the other way round."})+}++/// cross_check: input {sheetParts, board}. The sheets' designators against the board's.+pub fn cross_check(input: &Value) -> Value {+ let Some(sheet) = sheet_list(input) else { return crate::input::refuse("bad_args", "pass the sheets' parts as sheetParts") };+ let st_ = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let (list, board_only) = parts(&sheet, Some(&st_));+ let mut sheet_only: Vec<String> = list.iter().filter(|p| p.placed.is_none() && !p.no_bom).map(|p| p.designator.clone()).collect();+ sheet_only.sort_by_key(|d| natural_key(d));+ let matched = list.iter().filter(|p| p.placed.is_some()).count();+ json!({"success": true, "schematicComponents": list.len(), "boardComponents": matched + board_only.len(), "matched": matched,+ "onSheetNotOnBoard": sheet_only, "onBoardNotOnSheet": board_only,+ "_hint": "onSheetNotOnBoard: update the board from the schematic (update_pcb). onBoardNotOnSheet: parts placed by hand or left after a schematic change; remove them (remove_parts) or add them to a sheet. Parts kept out of the BOM by kind are not counted as missing from the board."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_bom_groups_by_part_number_and_checks_the_order() {+ let p = |d: &str, v: &str, params: Value| json!({"designator": d, "comment": v, "libRef": "R", "params": params});+ let sheet = vec![+ p("R10", "10k", json!({"MPN": "RC0603FR-0710KL", "Manufacturer": "Yageo", "LCSC": "C98220"})),+ p("R2", "10k", json!({"MPN": "RC0603FR-0710KL", "Manufacturer": "Yageo", "LCSC": "C98221"})),+ p("R1", "10k", json!({"MPN": "RC0603FR-0710KL", "Manufacturer": "Yageo"})),+ p("C1", "100n", json!({"Value": "100nF"})),+ p("TP1", "TP", json!({"MPN": "none (PCB copper)"})),+ p("U1", "MCU", json!([{"name": "MPN", "value": "RP2040"}, {"name": "DNP", "value": "yes"}])),+ json!({"designator": "R?", "comment": "x"}),+ json!({"designator": "H1", "comment": "hole", "excludeFromBom": true}),+ ];+ let board = json!({"components": [{"ref": "R1", "pattern": "R_0603", "x": 1.0, "y": 2.0, "rotation": 450.0, "side": "top"}, {"ref": "R2", "pattern": "R_0603", "x": 3.0, "y": 2.0, "rotation": 0.0, "side": "bottom"}, {"ref": "J9", "pattern": "X", "x": 0.0, "y": 0.0}]});+ let r = bom(&json!({"sheetParts": sheet, "board": board, "args": {"boards": 5, "variant": {"name": "lite", "notFitted": ["C1"]}}}));+ // R1, R2, R10 on one line in natural order; TP1 its own line, not purchased; U1 and C1 not fitted; H1 excluded+ assert_eq!(r["lines"][0]["designators"], json!(["R1", "R2", "R10"]), "{r}");+ assert_eq!(r["lines"][0]["quantity"], 3);+ assert_eq!(r["lineCount"], 2);+ assert_eq!(r["checks"]["inconsistent"][0]["field"], "lcsc");+ assert_eq!(r["checks"]["dnp"], json!(["C1", "U1"]));+ assert_eq!(r["checks"]["excludedKinds"], json!(["H1"]));+ assert_eq!(r["checks"]["notPurchased"], json!(["TP1"]));+ assert_eq!(r["checks"]["boardNotOnSheet"], json!(["J9"]));+ assert_eq!(r["checks"]["sheetNotOnBoard"], json!(["C1", "R10", "TP1", "U1"]));+ let file = |n: &str| r["files"].as_array().unwrap().iter().find(|f| f["name"] == n).unwrap()["text"].as_str().unwrap().to_string();+ assert!(file("cpl-jlcpcb.csv").contains("R1,1.0000mm,2.0000mm,Top,90\r\n") && file("cpl-jlcpcb.csv").contains("R2,3.0000mm,2.0000mm,Bottom,0\r\n"), "{}", file("cpl-jlcpcb.csv"));+ assert!(file("bom-mouser.csv").contains(",RC0603FR-0710KL,Yageo,15,\"R1,R2,R10\""), "{}", file("bom-mouser.csv"));+ assert!(!file("bom-jlcpcb.csv").contains("TP1"));+ let x = cross_check(&json!({"sheetParts": [p("R1", "", json!({})), p("R2", "", json!({}))], "board": {"components": [{"ref": "R1"}, {"ref": "J9"}], "pads": []}}));+ assert_eq!((x["matched"].clone(), x["onSheetNotOnBoard"].clone(), x["onBoardNotOnSheet"].clone()), (json!(1), json!(["R2"]), json!(["J9"])), "{x}");+ }+}
bridge-rs/vendor/adom-eda-checks/src/lib.rs+4−1@@ -10,6 +10,7 @@ use serde_json::Value; pub mod assembly; pub mod autoclass; pub mod bodies;+pub mod bom; pub mod coppermap; pub mod cost; pub mod current;@@ -40,7 +41,7 @@ pub mod writers; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); /// The checks this build answers, by standard verb name.-pub const CHECKS: &[&str] = &["assembly_check", "auto_classes", "board_report", "check_clearance", "check_orientation", "copper_balance", "current_capacity", "estimate_cost", "fab_check", "find_space", "footprint_from_land_pattern", "height_check", "impedance", "length_tune", "lint_library", "net_lengths", "panelize", "pin_pad_check", "place_decoupling", "placement_check", "plan_fanout", "plan_route", "return_path", "review_board", "route_pair", "schematic_review", "silk_designators", "teardrops", "thermal_vias", "via_fence"];+pub const CHECKS: &[&str] = &["assembly_check", "auto_classes", "board_report", "bom", "check_clearance", "check_orientation", "copper_balance", "cross_check", "current_capacity", "estimate_cost", "fab_check", "find_space", "footprint_from_land_pattern", "height_check", "impedance", "length_tune", "lint_library", "net_lengths", "panelize", "pin_pad_check", "place_decoupling", "placement_check", "plan_fanout", "plan_route", "return_path", "review_board", "route_pair", "schematic_review", "silk_designators", "teardrops", "thermal_vias", "via_fence"]; /// Run one check or writer by its standard name. The reply carries `engine`. pub fn run(check: &str, input: &Value) -> Value {@@ -55,9 +56,11 @@ fn answer(check: &str, input: &Value) -> Value { "assembly_check" => assembly::assembly_check(input), "auto_classes" => autoclass::auto_classes(input), "board_report" => report::board_report(input),+ "bom" => bom::bom(input), "check_clearance" => placetools::check_clearance(input), "check_orientation" => space::check_orientation(input), "copper_balance" => coppermap::copper_balance(input),+ "cross_check" => bom::cross_check(input), "current_capacity" => current::current_capacity(input), "estimate_cost" => cost::estimate_cost(input), "find_space" => space::find_space(input),
dev-skills/altium-bridge-test/run_verb_tests.py+19−1@@ -110,6 +110,8 @@ def matrix(w): # ---- phase 1: lifecycle ------------------------------------------------------------------ M["launch"] = dict(phase=1, timeout=300, **ok(waitSec=150)) M["agent_start"] = dict(phase=1, **ok())+ # 0.2.88: the standard's tool_update: every Altium here with its exact build (read-only)+ M["tool_update"] = dict(phase=1, timeout=150, **ok(action="check"), check=lambda d: len(d.get("installs") or []) >= 1 and all(i.get("version") for i in d["installs"]) and "offered" in d) # 0.2.85: the standard's prewarm, with Altium up and the agent resident: idempotent, ready, nothing opened M["prewarm"] = dict(phase=1, timeout=150, **ok(), check=lambda d: d.get("ready") is True and any(x.get("step") == "agent" and x.get("done") for x in d.get("steps") or []))@@ -264,6 +266,10 @@ def matrix(w): M["apply_pours"] = dict(phase=3.5, timeout=300, **ok(pours=[{"net": "GND", "layer": "B.Cu", "points": [[1, 1], [39, 1], [39, 19], [1, 19]], "connect": "relief"}])) M["pour_state"] = dict(phase=3.5, **ok())+ # 0.2.88: the standard's edit_pours on the GND pour apply_pours just made: islands, order, and a clearance rule+ M["edit_pours"] = dict(phase=3.5, timeout=600, **ok(filePath=LB, pours=[{"net": "GND", "layer": "B.Cu", "set": {"removeIslands": True, "pourIndex": 1, "clearanceMm": 0.3}}]),+ check=lambda d: len(d.get("edited") or []) >= 1 and all(w.get("ok") for w in d.get("rulesWritten") or [{}])+ and not [r for r in d.get("results") or [] if str(r).startswith("err")]) M["repour"] = dict(phase=3.5, timeout=300, **ok()) M["remove_pours"] = dict(phase=3.5, **ok(pours="all")) M["set_outline"] = dict(phase=3.5, **ok(outline={"rect": [0, 0, 40, 20], "cornerRadius": 1}))@@ -313,7 +319,11 @@ def matrix(w): # build_schematic made LP with LS (U1, U2) and LB. A third part goes on the sheet as U?, gets a # number, wires and a comment; update_pcb then carries it to the board (a REAL change order: the # first one on a scripted board answers the component-links prompt), and autoroute routes it.- M["bom"] = dict(phase=3.5, timeout=300, **ok(projectPath=LP, write=False, timeout=240), check=lambda d: (d.get("lineCount") or 0) >= 1)+ # 0.2.88: bom runs on the engine; and cross_check's project form (every sheet of the lane project against its board),+ # which needs the lane project this phase builds, rides on this entry's check+ M["bom"] = dict(phase=3.5, timeout=300, **ok(projectPath=LP, write=False, timeout=240),+ check=lambda d: (d.get("lineCount") or 0) >= 1 and isinstance(d.get("checks"), dict)+ and isinstance(w["call"]("altium_cross_check", {"projectPath": LP}).get("matched"), int)) M["sheet_params"] = dict(phase=3.5, **ok(projectPath=LP, designators=["U1"], params={"BatteryParam": "1"}), check=lambda d: d.get("updated") == ["U1"]) M["doc_params"] = dict(phase=3.5, **ok(sheet=LS, set={"Revision": "B"})) M["sch_place_part"] = dict(phase=3.5, **ok(sheet=LS, library=SL, symbol="TST_SOIC8", designator="U?", x=8000, y=2000))@@ -456,6 +466,11 @@ def matrix(w): M["project_snapshot"] = dict(phase=3.5, **ok(project=LP, label="battery", pdfs=False), check=lambda d: len(d.get("files") or []) >= 3) M["render_board_3d"] = dict(phase=3.5, timeout=700, **anyo("a 3D picture of the lane board, or a named refusal", filePath=LB, width=800)) M["render_board"] = dict(phase=3.5, timeout=700, **anyo("the standard's name for render_board_3d: a picture or a named refusal", filePath=LB, side="top", width=800))+ # 0.2.88: the standard's export_3d through Altium's own Parasolid exporter (File > Export, its dialogs answered)+ M["export_3d"] = dict(phase=3.5, timeout=360, **ok(filePath=LB, format="parasolid", outputDir=D + "/export"),+ check=lambda d: (d.get("bytes") or 0) > 1000 and str(d.get("path", "")).lower().endswith(".x_t"))+ # 0.2.88: the standard's import_design: a format the bridge does not drive yet is refused by name+ M["import_design"] = dict(phase=3.5, **ref("PADS is not driven yet: a named refusal", format="pads", filePath=LB)) M["render_board_layers"] = dict(phase=3.5, timeout=700, **ok(filePath=LB, preset="top_copper", dpi=100), check=lambda d: str(d.get("path", "")).endswith(".png")) M["library_views"] = dict(phase=3.5, timeout=600, **anyo("symbol and footprint pictures of TST_SOIC8", libraryPath=SL, parts=["TST_SOIC8"], views=["symbol", "footprint"])) M["export_library_part"] = dict(phase=3.5, timeout=600, **anyo("the symbol and footprint in their own libraries, model missing named", part="TST_SOIC8", libraryPath=SL, outputDir=D + "/export"))@@ -481,6 +496,9 @@ def matrix(w): M["export_spice"] = dict(phase=4, timeout=900, **ok(schematic=SIM), check=lambda d: len(d.get("elements") or []) >= 8 and bool(d.get("analyses"))) M["generate_body"] = dict(phase=4, **ok(family="qfn", outputPath=D + "/bodies/QFN16.step", marking="STM32\nG031"), check=lambda d: abs(((d.get("bboxMm") or {}).get("x") or 0) - 4.0) < 0.01 and d.get("marking") and not d.get("notApplied"))+ # 0.2.88: the standard's import_step: generate_body's STEP placed with the lane board as free geometry, 5 mm up+ M["import_step"] = dict(phase=4, timeout=200, **ok(filePath=LB, stepPath=D + "/bodies/QFN16.step", at=[20, 10], standoffMm=5),+ check=lambda d: len(d.get("boxMm") or []) == 4 and (d.get("heightMm") or 0) > 0 and isinstance(d.get("meets"), list)) M["export_step"] = dict(phase=4, timeout=300, **anyo("STEP of the battery board", filePath=PD, output=D + "/battery.step")) M["export_bom"] = dict(phase=4, **anyo("missing OutJob: named refusal (the demo OutJob opens its .xlsx on screen)", outjobPath=D + "/missing.OutJob")) M["export_gerber"] = dict(phase=4, **anyo("missing OutJob: named refusal", outjobPath=D + "/missing.OutJob"))
package.json+8−2@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.87",+ "version": "0.2.88", "type": "app", "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.", "tags": [@@ -278,7 +278,13 @@ "what did altium complain about", "check my altium schematic for dangling wires", "altium schematic label not on a wire",- "overlapping symbols altium schematic"+ "overlapping symbols altium schematic",+ "export my altium board as parasolid",+ "altium vrml export",+ "edit a polygon pour in altium",+ "place an enclosure step with my altium board",+ "does the board fit the enclosure altium",+ "which altium version is installed" ], "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.", "sample_prompts": [
page.json+8−2@@ -4,7 +4,7 @@ "type": "app", "title": "Altium Bridge: AI for Altium Designer", "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",- "version": "0.2.87",+ "version": "0.2.88", "hero": { "type": "image", "path": "screenshots/hero.png"@@ -270,7 +270,13 @@ "what did altium complain about", "check my altium schematic for dangling wires", "altium schematic label not on a wire",- "overlapping symbols altium schematic"+ "overlapping symbols altium schematic",+ "export my altium board as parasolid",+ "altium vrml export",+ "edit a polygon pour in altium",+ "place an enclosure step with my altium board",+ "does the board fit the enclosure altium",+ "which altium version is installed" ], "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.", "metadata": {},
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.87+0.2.88
src/agent/AdomAgent.pas.tmpl+142@@ -4645,6 +4645,48 @@ End; { bom_placement: every component's footprint, side and reference point relative to the board origin, for a pick-and-place file. Lean on purpose (no pads, no nets): a large board's full read takes minutes. x/y are RAW coords from the origin (10000 per mil), rotation in thousandths of a degree (locale-free). }+{ import_step: a STEP placed with the board as free 3D geometry (an enclosure, a bracket) for fit checks: a 3D body of+ the board itself, on a mechanical layer, belonging to no part. path= the STEP; x= y= mm (the board model's frame) where+ the STEP's own origin lands; rx= ry= rz= degrees; standoff= mm; layer= the mechanical layer id; side=top|bottom.+ Answers the body's extent (raw, absolute) and its height. }+Function CmdImportStep(Lines : TStringList) : String;+Var+ Board : IPCB_Board;+ Body : IPCB_ComponentBody;+ Mdl : IPCB_Model;+ R : TCoordRect;+ Path : String;+ L : Integer;+Begin+ Board := PCBServer.GetCurrentPCBBoard;+ If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_board') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;+ Path := Param(Lines, 'path');+ If Not FileExists(Path) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','file_not_found') + ',' + JStr('error','no STEP at ' + Path) + '}'; Exit; End;+ L := StrToIntDef(Param(Lines, 'layer'), eMechanical1);+ PCBServer.PreProcess;+ Body := PCBServer.PCBObjectFactory(eComponentBodyObject, eNoDimension, eCreate_Default);+ { a body with no layer is dropped on add, and an invisible one reads as missing (see add_body) }+ Body.Layer := L;+ Board.LayerStack.LayerObject[L].MechanicalLayerEnabled := True;+ Board.LayerIsDisplayed[L] := True;+ Body.BodyOpacity3D := 1.0;+ Mdl := Body.ModelFactory_FromFilename(Path, False);+ If Mdl = Nil Then Begin PCBServer.PostProcess; Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','model_not_loaded') + ',' + JStr('error','Altium could not load ' + Path) + '}'; Exit; End;+ Try Mdl.SetState(AdomFloat(Param(Lines, 'rx')), AdomFloat(Param(Lines, 'ry')), AdomFloat(Param(Lines, 'rz')), MmC(Param(Lines, 'standoff'))); Except End;+ Body.SetState_FromModel;+ Body.Model := Mdl;+ If Param(Lines, 'side') = 'bottom' Then Body.BodyProjection := eBoardSide_Bottom Else Body.BodyProjection := eBoardSide_Top;+ Body.MoveByXY(MmC(Param(Lines, 'x')), MmC(Param(Lines, 'y')));+ Board.AddPCBObject(Body);+ PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Body.I_ObjectAddress);+ PCBServer.PostProcess;+ Board.ViewManager_FullUpdate;+ R := Body.BoundingRectangle;+ Result := '{' + JRaw('ok','true') + ',' + JRaw('box', '[' + IntToStr(R.Left) + ',' + IntToStr(R.Bottom) + ',' + IntToStr(R.Right) + ',' + IntToStr(R.Top) + ']') + ',' ++ JRaw('standoff', IntToStr(Body.StandoffHeight)) + ',' + JRaw('height', IntToStr(Body.OverallHeight)) + ',' + JRaw('layer', IntToStr(Body.Layer)) + ',' ++ JStr('id', IntToStr(Body.I_ObjectAddress)) + '}';+End;+ Function CmdBomPlacement(Lines : TStringList) : String; Var Board : IPCB_Board;@@ -6785,6 +6827,104 @@ Begin RegisterPrim(Board, Reg); End; +{ The polygon named Name, Nil when none }+Function PolyByName(Board : IPCB_Board; Name : String) : IPCB_Polygon;+Var+ BIt : IPCB_BoardIterator;+ Poly : IPCB_Polygon;+Begin+ Result := Nil;+ BIt := Board.BoardIterator_Create;+ BIt.AddFilter_ObjectSet(MkSet(ePolyObject));+ BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_Method(eProcessAll);+ Poly := BIt.FirstPCBObject;+ While (Poly <> Nil) And (Result = Nil) Do+ Begin+ If Poly.Name = Name Then Result := Poly;+ Poly := BIt.NextPCBObject;+ End;+ Board.BoardIterator_Destroy(BIt);+End;++{ edit_pour: change existing polygons in place. Payload lines "name|key|value": net, layer (id), hatch (solid, 45, 90,+ none), track (raw width of hatch tracks), grid (raw), dead (0/1: remove dead copper), islands (0/1: remove small+ islands), neck (raw neck width; 0 off), over (same | none: pour over same-net objects), index (pour order),+ connect (D|R|N,width,gap,entries raw: the pour's PolygonConnect rule). Each answers ok:<key> or err:<why>, in order;+ every polygon touched is rebuilt. }+Function CmdEditPour(Lines : TStringList; Payload : String) : String;+Var+ Board : IPCB_Board;+ Poly : IPCB_Polygon;+ Net : IPCB_Net;+ Ops, Done : TStringList;+ Op, Nm, Key, V, Res, Results : String;+ I : Integer;+Begin+ Board := PCBServer.GetCurrentPCBBoard;+ If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_board') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;+ Ops := TStringList.Create; Ops.Text := Payload;+ Done := TStringList.Create;+ Results := '';+ PCBServer.PreProcess;+ For I := 0 To Ops.Count - 1 Do+ Begin+ Op := Ops[I];+ If Trim(Op) = '' Then Continue;+ Nm := FieldP(Op, 1); Key := FieldP(Op, 2); V := FieldP(Op, 3);+ Poly := PolyByName(Board, Nm);+ Res := 'ok:' + Key;+ If Poly = Nil Then Res := 'err:no pour named ' + Nm+ Else If Key = 'connect' Then SetPourConnect(Board, Nm, Field(V, 1), AdomInt(Field(V, 2)), AdomInt(Field(V, 3)), AdomInt(Field(V, 4)))+ Else+ Begin+ Poly.BeginModify;+ If Key = 'net' Then+ Begin+ Net := FindNet(Board, V);+ If Net = Nil Then Res := 'err:no net ' + V Else Poly.Net := Net;+ End+ Else If Key = 'layer' Then Poly.Layer := AdomInt(V)+ Else If Key = 'hatch' Then+ Begin+ If V = 'solid' Then Poly.PolyHatchStyle := ePolySolid+ Else If V = '45' Then Poly.PolyHatchStyle := ePolyHatch45+ Else If V = '90' Then Poly.PolyHatchStyle := ePolyHatch90+ Else If V = 'none' Then Poly.PolyHatchStyle := ePolyNoHatch+ Else Res := 'err:hatch is solid, 45, 90 or none';+ End+ Else If Key = 'track' Then Poly.TrackSize := AdomInt(V)+ Else If Key = 'grid' Then Poly.Grid := AdomInt(V)+ Else If Key = 'dead' Then Poly.RemoveDead := V = '1'+ Else If Key = 'islands' Then Poly.RemoveIslandsByArea := V = '1'+ Else If Key = 'neck' Then+ Begin+ Poly.RemoveNarrowNecks := AdomInt(V) > 0;+ If AdomInt(V) > 0 Then Poly.NeckWidthThreshold := AdomInt(V);+ End+ Else If Key = 'over' Then+ Begin+ If V = 'same' Then Poly.PourOver := ePolygonPourOver_SameNet Else Poly.PourOver := ePolygonPourOver_None;+ End+ Else If Key = 'index' Then Poly.PourIndex := AdomInt(V)+ Else Res := 'err:unknown key ' + Key;+ Poly.EndModify;+ End;+ If (Poly <> Nil) And (Done.IndexOf(Nm) < 0) Then Done.Add(Nm);+ If Results <> '' Then Results := Results + ',';+ Results := Results + '"' + JsonEsc(Res) + '"';+ End;+ For I := 0 To Done.Count - 1 Do+ Begin+ Poly := PolyByName(Board, Done[I]);+ If Poly <> Nil Then Begin Poly.Rebuild; Poly.GraphicallyInvalidate; End;+ End;+ PCBServer.PostProcess;+ Board.ViewManager_FullUpdate;+ Result := '{' + JRaw('ok','true') + ',' + JRaw('results', '[' + Results + ']') + ',' + JRaw('pours', IntToStr(Done.Count)) + '}';+ Ops.Free; Done.Free;+End;+ Function CmdApplyPours(Lines : TStringList; Payload : String) : String; Var Board : IPCB_Board;@@ -10268,6 +10408,7 @@ Begin Else If Cmd = 'edit_fp' Then Result := CmdEditFp(Lines, Payload) Else If Cmd = 'close_document' Then Result := CmdCloseDocument(Lines) Else If Cmd = 'messages' Then Result := CmdMessages(Lines)+ Else If Cmd = 'import_step' Then Result := CmdImportStep(Lines) Else If Cmd = 'eval' Then Result := CmdEval(Lines, Payload) Else If Cmd = 'io_bench' Then Result := CmdIoBench(Lines) Else If Cmd = 'read_board' Then Result := CmdReadBoard(Lines)@@ -10342,6 +10483,7 @@ Begin Else If Cmd = 'routing_state' Then Result := CmdRoutingState(Lines) Else If Cmd = 'edit_board' Then Result := CmdEditBoard(Lines, Payload) Else If Cmd = 'apply_pours' Then Result := CmdApplyPours(Lines, Payload)+ Else If Cmd = 'edit_pour' Then Result := CmdEditPour(Lines, Payload) Else If Cmd = 'pour_state' Then Result := CmdPourState(Lines) Else If Cmd = 'rebuild_pours' Then Result := CmdRebuildPours(Lines) Else If Cmd = 'remove_pours' Then Result := CmdRemovePours(Lines, Payload)
src/bridge.json+7−2@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.87",+ "version": "0.2.88", "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.", "homepage": "https://wiki.adom.inc/adom/altium-bridge", "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -204,6 +204,11 @@ "altium_render_board", "altium_log_tail", "altium_sch_batch",+ "altium_import_step",+ "altium_edit_pours",+ "altium_export_3d",+ "altium_tool_update",+ "altium_import_design", "altium_route_pair", "altium_routing_drc", "altium_routing_state",@@ -297,7 +302,7 @@ "launch": 240, "panelize": 240, "impedance": 120,- "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900,+ "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 120, "import_design": 600, "height_check": 150, "copper_balance": 240, "return_path": 240,