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.86: sch_batch and log_tail (the standard's last two), engine 0.22.0 (schematic_review design checks, placement score)
18 files changed
+817−124
CHANGELOG.md+12README.md+6−4bridge-rs/src/logtail.rs+155bridge-rs/src/main.rs+3−1bridge-rs/src/schbatch.rs+144bridge-rs/src/schdoc.rs+3bridge-rs/src/schreview.rs+10−98bridge-rs/src/verbs.rs+13−1bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1bridge-rs/vendor/adom-eda-checks/README.md+2−2bridge-rs/vendor/adom-eda-checks/src/placement.rs+114−3bridge-rs/vendor/adom-eda-checks/src/schreview.rs+299−7dev-skills/altium-bridge-test/run_verb_tests.py+9package.json+6−2page.json+6−2src/BRIDGE_VERSION+1−1src/agent/AdomAgent.pas.tmpl+29src/bridge.json+4−2CHANGELOG.md+12@@ -1,5 +1,17 @@ # Changelog +## 0.2.86++- **The last two verbs of the standard** (EDA Bridge Standard #29, standard 0.27), so Altium answers all 247:+ - `altium_sch_batch`: a list of schematic edits applied to one sheet in order, all or nothing. Each op is a schematic verb with its own arguments (`sch_place_part`, `sch_connect_pins`, `sch_text` and fifteen more), seeing the sheet as the earlier ops left it. Altium edits the open sheet, so "nothing" is built from its undo: when an op fails, Undo runs once per op already applied, and the sheet's fingerprint (its parts and wiring) must match the one taken before. Then the answer is `op_failed` with `restored: true`; if the fingerprint does not match, it is `partial`. `ercBefore` / `ercAfter` count the sheet's Messages from a compile before and after (`erc: false` skips them), and `dryRun` answers the plan.+ - Measured on the battery's lane sheet: two texts went in as one batch, and a batch whose second op named pins that do not exist was taken back, leaving the sheet as it was.+ - `altium_log_tail`: what Altium said about itself since an offset, from its Messages panel and its own log files. The panel empties on every compile, so each call captures what is new into the bridge's own file, and offsets are bytes of that file: they stay valid across compiles. `errorsOnly` keeps warnings and errors. Measured: the first call read the panel's "Unconnected Port N1" warning and Altium's three log files, and a second call from `next` returned nothing new.++- **The standard's engine 0.22.0** (adom-eda-checks, standard 0.27.0, vendored as published):+ - `schematic_review` now runs on it, with KiCad's design checks: a floating reset or enable pin, I2C with no pull-up, an LED with no resistor, a regulator without its capacitors, a no-connect flag on a wired pin, a designator unannotated or used twice, and a rail with no bulk capacitor, each with a message and a fix. Altium's own copy of the pin checks is gone; the engine runs the same ones.+ - The sheet parts it reads now carry the standard's `libRef` and each part's `Value` parameter, beside `libReference` and `comment`, so the regulator and LED checks know what a part is.+ - `placement_check` gains a score (0 to 100, grade A to F) weighing overlaps, off-board parts, connectors deep inside the board, decoupling far from its IC, and the ratsnest's length.+ ## 0.2.85 - **Four verbs new in the standard** (EDA Bridge Standard #29, standard 0.26), so Altium answers all of it again:
README.md+6−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 -263 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+265 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. 263 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 265 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 263 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 265 `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 263 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 265 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -257,6 +257,8 @@ All 263 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_verb_times`: Measured run times of this bridge's verbs on this machine: per verb the count, p50, p90, max, last and failures, from its own run log, slowest p90 first. - `altium_prewarm`: Get this machine ready for a fast first call: find the install, write the agent's script, and with Altium running answer its first-run boxes and make the agent resident. - `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_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/src/logtail.rsadded+155@@ -0,0 +1,155 @@+//! log_tail: what Altium said about itself since an offset (EDA Bridge Standard #29), so a verb that looks+//! successful while Altium complains is caught. Altium's voice is its Messages panel (compile, ERC, DRC and script+//! messages) and its own log files (start-up and shut-down traces). The panel empties on every compile, so its+//! offsets would mean nothing: each call captures what is new into this bridge's own file, and offsets are bytes of+//! that file. The dialogs the bridge answered stay in dialog_log, so the two never double up.+use serde_json::{json, Value};+use std::io::{Read, Seek, SeekFrom, Write};+use std::path::PathBuf;+use std::time::Duration;++fn store() -> PathBuf {+ let base = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into());+ let d = PathBuf::from(base).join(".adom");+ let _ = std::fs::create_dir_all(&d);+ d+}+fn capture_path() -> PathBuf { store().join("altium-log-tail.jsonl") }+fn state_path() -> PathBuf { store().join("altium-log-tail.state.json") }++/// A Messages class or a log line, as the standard's level.+pub fn level(class_or_text: &str) -> &'static str {+ let l = class_or_text.to_ascii_lowercase();+ if l.contains("fatal") || l.contains("error") || l.contains("exception") || l.contains("access violation") { "error" }+ else if l.contains("warning") || l.contains("warn") { "warning" } else { "info" }+}++/// The messages new since the last snapshot: the panel only grows between compiles, so when the old snapshot is a+/// prefix of the new one the rest is new; otherwise the panel was cleared and refilled, and all of it is new. Pure.+pub fn new_messages<'a>(old: &[String], now: &'a [Value]) -> Vec<&'a Value> {+ let keys: Vec<String> = now.iter().map(|m| m.to_string()).collect();+ let skip = if old.len() <= keys.len() && old.iter().zip(&keys).all(|(a, b)| a == b) { old.len() } else { 0 };+ now[skip..].iter().collect()+}++/// Entries from the capture's text starting at a byte offset, at most max_bytes of it, whole lines only. Pure.+pub fn read_from(text: &str, since: usize, max_bytes: usize, errors_only: bool) -> (Vec<Value>, usize, bool) {+ let start = since.min(text.len());+ let mut at = start;+ let mut out = Vec::new();+ let mut truncated = false;+ for line in text[start..].split_inclusive('\n') {+ if !line.ends_with('\n') { break; } // a line still being written+ if at + line.len() - start > max_bytes { truncated = true; break; }+ at += line.len();+ let Ok(v) = serde_json::from_str::<Value>(line.trim_end()) else { continue };+ if errors_only && v["level"] == "info" { continue; }+ out.push(v);+ }+ (out, at, truncated)+}++/// Capture what is new into the file: the Messages panel (with Altium running) and Altium's own log files.+fn capture() -> Value {+ let mut state: Value = std::fs::read_to_string(state_path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}));+ let mut lines: Vec<Value> = Vec::new();+ let now = crate::support::now();+ let mut panel = "not running";+ if crate::health::is_running() && crate::agent::is_alive() {+ let r = crate::agent::call("messages", &[], None, Duration::from_secs(30));+ if let Some(msgs) = r.get("data").filter(|d| d["ok"] == json!(true)).and_then(|d| d["messages"].as_array()).cloned() {+ let old: Vec<String> = state["messages"].as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_string)).collect();+ for m in new_messages(&old, &msgs) {+ let class = m["class"].as_str().unwrap_or("");+ lines.push(json!({"at": now, "source": "messages", "level": level(class), "text": m["text"], "class": class, "document": m["document"], "from": m["source"]}));+ }+ state["messages"] = json!(msgs.iter().map(|m| m.to_string()).collect::<Vec<_>>());+ panel = "read";+ } else { panel = "agent did not answer"; }+ } else if crate::health::is_running() { panel = "agent not resident"; }+ // Altium's log files: the per-install folders under LOCALAPPDATA\Altium+ let la = std::env::var("LOCALAPPDATA").unwrap_or_default();+ let mut files_read = Vec::new();+ for d in std::fs::read_dir(PathBuf::from(&la).join("Altium")).into_iter().flatten().flatten() {+ if !d.file_name().to_string_lossy().starts_with("Altium Designer") { continue; }+ for f in std::fs::read_dir(d.path()).into_iter().flatten().flatten() {+ let p = f.path();+ if !p.extension().map(|x| x.eq_ignore_ascii_case("log")).unwrap_or(false) { continue; }+ let key = p.to_string_lossy().to_string();+ let len = f.metadata().map(|m| m.len()).unwrap_or(0);+ let seen = state["files"][&key].as_u64().unwrap_or(0);+ // a log Altium rewrote from the start is read again from the start+ let from = if len < seen { 0 } else { seen };+ if len > from {+ if let Ok(mut fh) = std::fs::File::open(&p) {+ let mut buf = Vec::new();+ if fh.seek(SeekFrom::Start(from)).is_ok() && fh.take(len - from).read_to_end(&mut buf).is_ok() {+ for l in String::from_utf8_lossy(&buf).lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with("---")) {+ lines.push(json!({"at": now, "source": p.file_name().map(|n| n.to_string_lossy().to_string()), "level": level(l), "text": l}));+ }+ }+ }+ }+ state["files"][&key] = json!(len);+ files_read.push(key);+ }+ }+ if !lines.is_empty() {+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(capture_path()) {+ for l in &lines { let _ = writeln!(f, "{l}"); }+ }+ }+ let _ = std::fs::write(state_path(), state.to_string());+ json!({"messagesPanel": panel, "logFiles": files_read.len(), "captured": lines.len()})+}++/// altium_log_tail {sinceOffset?, maxBytes?, errorsOnly?}+pub fn log_tail(args: &Value) -> Value {+ let cap = capture();+ let since = args.get("sinceOffset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;+ let max = args.get("maxBytes").and_then(|v| v.as_u64()).unwrap_or(200_000) as usize;+ let errors_only = args.get("errorsOnly").and_then(|v| v.as_bool()).unwrap_or(false);+ let text = std::fs::read_to_string(capture_path()).unwrap_or_default();+ let (entries, next, truncated) = read_from(&text, since, max, errors_only);+ json!({"success": true, "entries": entries, "next": next, "truncated": truncated, "sources": cap,+ "_hint": "Pass next as sinceOffset to see only what is new. Messages come from Altium's Messages panel (read while the agent is resident; compile, ERC and DRC fill it) and lines from Altium's own log files; dialogs the bridge answered are in altium_dialog_log, not here."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn levels_from_classes_and_lines() {+ assert_eq!(level("[Error]"), "error");+ assert_eq!(level("[Fatal Error]"), "error");+ assert_eq!(level("[Warning]"), "warning");+ assert_eq!(level("T+: 15 Closing Documents"), "info");+ }++ #[test]+ fn only_messages_not_seen_before() {+ let m = |t: &str| json!({"class": "[Warning]", "text": t});+ let now = vec![m("a"), m("b"), m("c")];+ let old: Vec<String> = vec![m("a").to_string(), m("b").to_string()];+ assert_eq!(new_messages(&old, &now).len(), 1);+ // the panel was cleared and refilled: everything is new+ let old: Vec<String> = vec![m("x").to_string()];+ assert_eq!(new_messages(&old, &now).len(), 3);+ assert_eq!(new_messages(&now.iter().map(|v| v.to_string()).collect::<Vec<_>>(), &now).len(), 0);+ }++ #[test]+ fn offsets_are_bytes_of_whole_lines() {+ let text = "{\"level\":\"info\",\"text\":\"a\"}\n{\"level\":\"error\",\"text\":\"b\"}\n{\"level\":\"warning\",\"te";+ let (all, next, t) = read_from(text, 0, 100_000, false);+ assert_eq!((all.len(), t), (2, false));+ assert_eq!(&text[next..], "{\"level\":\"warning\",\"te");+ let (errs, _, _) = read_from(text, 0, 100_000, true);+ assert_eq!(errs.len(), 1);+ let (none, again, _) = read_from(text, next, 100_000, false);+ assert_eq!((none.len(), again), (0, next));+ let (one, _, cut) = read_from(text, 0, 30, false);+ assert_eq!((one.len(), cut), (1, true));+ }+}
bridge-rs/src/main.rs+3−1@@ -34,6 +34,8 @@ mod current; mod fpupdate; mod liblint; mod pos;+mod logtail;+mod schbatch; mod impedance; mod inspect; mod lengths;@@ -71,7 +73,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.85";+pub const BRIDGE_VERSION: &str = "0.2.86"; 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/schbatch.rsadded+144@@ -0,0 +1,144 @@+//! sch_batch: a list of the standard's schematic edits on one sheet, all or nothing (EDA Bridge Standard #29). Altium+//! edits the open sheet live, not a file, so "nothing" is built from its undo: the ops run in order, each one seeing the+//! sheet as the earlier ones left it; when one fails, Altium's Undo runs once for every op already applied and the+//! sheet's fingerprint (its parts and wiring) must match the one taken before the batch. If it does not, the batch+//! answers partial with the ops that ran, as the standard allows for a tool that cannot take a batch back.+use serde_json::{json, Value};+use std::time::Duration;++/// The schematic verbs a batch may run: they each edit one sheet, named by `sheet`, and leave it unsaved.+pub const OPS: &[&str] = &["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"];++/// Each op's verb and its arguments, with the batch's sheet (and project, for annotate) filled in. Pure.+pub fn plan(ops: &[Value], sheet: &str, project: Option<&str>) -> Result<Vec<(String, Value)>, (usize, String)> {+ let mut out = Vec::new();+ for (i, o) in ops.iter().enumerate() {+ let Some(name) = o["op"].as_str() else { return Err((i, "every op needs op: the name of a schematic verb".into())) };+ let name = name.strip_prefix("altium_").unwrap_or(name);+ if !OPS.contains(&name) { return Err((i, format!("{name} is not a schematic edit a batch runs (one of {})", OPS.join(", ")))); }+ let mut a = o.clone();+ if let Some(m) = a.as_object_mut() {+ m.remove("op");+ if name == "annotate" {+ match project { Some(p) => { m.entry("projectPath").or_insert(json!(p)); } None => return Err((i, "annotate needs the sheet's project: none beside the sheet lists it".into())) }+ } else {+ // an op names the batch's sheet or none; another sheet would escape the rollback+ if let Some(s) = m.get("sheet").and_then(|v| v.as_str()) {+ if crate::agent::win_path(s).to_lowercase() != crate::agent::win_path(sheet).to_lowercase() { return Err((i, format!("op {i} names another sheet ({s}): a batch edits one sheet"))); }+ }+ m.insert("sheet".into(), json!(sheet));+ }+ m.insert("save".into(), json!(false));+ }+ out.push((name.to_string(), a));+ }+ Ok(out)+}++/// The sheet's fingerprint: its parts (designator, symbol, place, turn, parameters) and wiring items, ids included.+fn fingerprint(sheet: &str) -> Option<String> {+ let parts = crate::verbs::dispatch("schematic_data", &json!({"filePath": sheet}), &[]);+ let items = crate::verbs::dispatch("sch_items", &json!({"sheet": sheet}), &[]);+ if items.get("success").and_then(|b| b.as_bool()) == Some(false) { return None; }+ let comps: Vec<Value> = parts.get("data").and_then(|d| d["components"].as_array()).or(parts["components"].as_array()).cloned().unwrap_or_default().iter()+ .map(|c| json!([c["designator"], c["libReference"], c["xMil"], c["yMil"], c["orientation"], c["params"]])).collect();+ let mut wiring = items.clone();+ if let Some(m) = wiring.as_object_mut() { m.retain(|k, _| matches!(k.as_str(), "wires" | "buses" | "busEntries" | "labels" | "powerPorts" | "junctions" | "noConnects" | "texts" | "sheets")); }+ Some(crate::routing::fnv(&json!([comps, wiring]).to_string()))+}++/// Compile the project and count the Messages for this sheet by class.+fn erc_counts(project: &str, sheet: &str) -> Value {+ let r = crate::outputs::compile(&json!({"projectPath": project, "limit": 2000}));+ let name = std::path::Path::new(&sheet.replace('\\', "/")).file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();+ let mut by = serde_json::Map::new();+ for m in r["messages"].as_array().cloned().unwrap_or_default() {+ if !m["document"].as_str().unwrap_or("").to_lowercase().ends_with(&name) { continue; }+ let k = m["class"].as_str().unwrap_or("?").to_string();+ let n = by.get(&k).and_then(|v| v.as_i64()).unwrap_or(0) + 1;+ by.insert(k, json!(n));+ }+ json!(by)+}++/// The project beside the sheet that lists it.+fn project_of(sheet: &str) -> Option<String> {+ let p = std::path::PathBuf::from(sheet.replace('\\', "/"));+ let name = p.file_name()?.to_string_lossy().to_lowercase();+ std::fs::read_dir(p.parent()?).ok()?.flatten().map(|e| e.path())+ .filter(|f| f.extension().map(|x| x.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false))+ .find(|f| std::fs::read_to_string(f).map(|t| t.to_lowercase().lines().any(|l| l.starts_with("documentpath=") && l.ends_with(&name))).unwrap_or(false))+ .map(|f| f.to_string_lossy().to_string())+}++fn ok(r: &Value) -> bool { r.get("success").and_then(|b| b.as_bool()) == Some(true) && r.get("data").map(|d| d["ok"] != json!(false)).unwrap_or(true) }++/// altium_sch_batch {filePath | sheet, ops, dryRun?, erc?}+pub fn sch_batch(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let Some(sheet) = crate::support::s(args, "filePath").or_else(|| crate::support::s(args, "sheet")).filter(|p| p.to_lowercase().ends_with(".schdoc")) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .SchDoc) is required"});+ };+ let Some(ops) = args.get("ops").and_then(|v| v.as_array()).filter(|a| !a.is_empty()).cloned() else {+ return json!({"success": false, "errorCode": "bad_args", "error": "ops: [{op: a schematic verb, ...its arguments}] is required"});+ };+ let project = crate::support::s(args, "projectPath").or_else(|| project_of(&sheet));+ let steps = match plan(&ops, &sheet, project.as_deref()) {+ Ok(p) => p,+ Err((i, why)) => return json!({"success": false, "errorCode": "bad_op", "failedOp": i, "error": why, "mutated": false}),+ };+ if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {+ return json!({"success": true, "dryRun": true, "mutated": false, "plan": steps.iter().map(|(n, a)| json!({"op": n, "args": a})).collect::<Vec<_>>(),+ "_hint": "Every op is a schematic verb this batch runs, on this sheet. Call again without dryRun to apply them."});+ }+ if let Some(e) = crate::support::must_open(&sheet, 60) { return e; }+ let erc = args.get("erc").and_then(|v| v.as_bool()).unwrap_or(true) && project.is_some();+ let erc_before = if erc { erc_counts(project.as_deref().unwrap_or(""), &sheet) } else { Value::Null };+ let Some(before) = fingerprint(&sheet) else { return json!({"success": false, "errorCode": "sheet_unread", "error": "the sheet's items could not be read, so a failed batch could not be checked back: nothing was run"}) };+ let mut results = Vec::new();+ for (i, (name, a)) in steps.iter().enumerate() {+ let r = crate::verbs::dispatch(name, a, &[]);+ if ok(&r) { results.push(json!({"op": name, "output": r})); continue; }+ // take the batch back: Undo once per op applied, then the sheet must be as it was+ let applied = i;+ for _ in 0..applied {+ crate::agent::call("run_process", &[("process", "Sch:Undo".into()), ("params", "".into())], None, Duration::from_secs(30));+ }+ let back = fingerprint(&sheet);+ let restored = back.as_deref() == Some(before.as_str());+ let mut out = json!({"success": false, "errorCode": if restored { "op_failed" } else { "partial" }, "failedOp": i, "op": name,+ "error": r.get("error").cloned().unwrap_or(json!("the op failed")), "reply": r, "results": results,+ "mutated": !restored, "undone": applied, "restored": restored});+ out["_hint"] = json!(if restored { "The batch was taken back: the sheet is as it was before it. Fix failedOp and run the batch again." }+ else { "PARTIAL: the ops in results ran and Undo did not bring the sheet back to where it was. Read it (schematic_data, sch_items) before going on; Altium's Edit > Undo can step further back by hand." });+ return out;+ }+ let after = fingerprint(&sheet);+ let erc_after = if erc { erc_counts(project.as_deref().unwrap_or(""), &sheet) } else { Value::Null };+ json!({"success": true, "results": results, "mutated": after.as_deref() != Some(before.as_str()), "ercBefore": erc_before, "ercAfter": erc_after,+ "undoSteps": steps.len(),+ "_hint": "Applied in order on the open sheet, unsaved: altium_save {filePath} keeps it. Each op is one of Altium's undo steps (undoSteps). ercBefore and ercAfter are the sheet's Messages by class from a compile before and after (erc:false skips both)."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_plan_fills_the_sheet_and_refuses_what_it_cannot_take_back() {+ let ops = vec![json!({"op": "sch_place_part", "libReference": "RES"}), json!({"op": "altium_sch_connect_pins", "pairs": [{"from": "R9.1", "to": "U1.3"}]})];+ let p = plan(&ops, "C:/p/Main.SchDoc", None).unwrap();+ assert_eq!(p[0].0, "sch_place_part");+ assert_eq!(p[1].0, "sch_connect_pins");+ assert_eq!(p[1].1["sheet"], "C:/p/Main.SchDoc");+ assert_eq!(p[1].1["save"], false);+ assert!(p[1].1.get("op").is_none());+ assert_eq!(plan(&[json!({"op": "run_drc"})], "C:/p/Main.SchDoc", None).unwrap_err().0, 0);+ assert_eq!(plan(&[json!({"op": "sch_text", "sheet": "C:/p/Other.SchDoc"})], "C:/p/Main.SchDoc", None).unwrap_err().0, 0);+ assert!(plan(&[json!({"op": "sch_text", "sheet": "C:\\p\\main.SchDoc"})], "C:/p/Main.SchDoc", None).is_ok(), "the same sheet in another spelling");+ assert!(plan(&[json!({"op": "annotate"})], "C:/p/Main.SchDoc", None).is_err());+ assert_eq!(plan(&[json!({"op": "annotate"})], "C:/p/Main.SchDoc", Some("C:/p/P.PrjPcb")).unwrap()[0].1["projectPath"], "C:/p/P.PrjPcb");+ }+}
bridge-rs/src/schdoc.rs+3@@ -132,6 +132,9 @@ pub fn components(recs: &[BTreeMap<String, String>], with_pins: bool, with_param let mut o = Map::new(); o.insert("designator".into(), json!(kids.iter().find(|k| k.get("RECORD").map(|r| r.as_str()) == Some("34")).and_then(|k| k.get("TEXT").cloned()).unwrap_or_default())); o.insert("libReference".into(), json!(c.get("LIBREFERENCE").cloned().unwrap_or_default()));+ // the standard's names for the same (the engine's design checks read libRef and value, else comment)+ o.insert("libRef".into(), json!(c.get("LIBREFERENCE").cloned().unwrap_or_default()));+ o.insert("value".into(), json!(field("41", "Value").unwrap_or_default())); o.insert("comment".into(), json!(field("41", "Comment").unwrap_or_default())); o.insert("description".into(), json!(c.get("COMPONENTDESCRIPTION").cloned().unwrap_or_default())); o.insert("uniqueId".into(), json!(c.get("UNIQUEID").cloned().unwrap_or_default()));
bridge-rs/src/schreview.rs+10−98@@ -1,7 +1,7 @@ //! A schematic review before Update PCB: every placed pin from the project's sheet files (with its electrical type) //! against Altium's compiled netlist. Unconnected pins (power pins as errors), nets with one pin, outputs driving each //! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground.-use serde_json::{json, Map, Value};+use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; /// Altium's pin electrical types (the ELECTRICAL field).@@ -9,99 +9,11 @@ pub fn electrical(n: i64) -> &'static str { match n { 0 => "input", 1 => "io", 2 => "output", 3 => "open_collector", 4 => "passive", 5 => "hiz", 6 => "open_emitter", 7 => "power", _ => "unknown" } } -/// A pin's type from the sheet model: Altium's code, or the name the standard uses (Fusion also sends `supply`, a-/// supply symbol's pin that drives its net, and `not_connected`).-pub fn pin_type(v: &Value) -> String {- match v {- Value::Number(n) => electrical(n.as_i64().unwrap_or(-1)).to_string(),- Value::String(t) => match t.to_ascii_lowercase().replace(['-', ' '], "_").as_str() {- "bidirectional" | "bidi" | "i/o" => "io".into(),- "pwr" => "power".into(),- "sup" => "supply".into(),- "nc" => "not_connected".into(),- "oc" | "opencollector" => "open_collector".into(),- "pas" => "passive".into(),- "tri" | "tristate" | "3state" => "hiz".into(),- "in" => "input".into(),- "out" => "output".into(),- o => o.to_string(),- },- _ => "unknown".into(),- }-}- pub fn is_ground(net: &str) -> bool { let n = net.to_ascii_uppercase(); n == "GND" || n == "0V" || n == "VSS" || n == "AGND" || n == "DGND" || n == "PGND" || n == "GNDA" || n == "GNDD" || n.starts_with("GND_") || n.ends_with("_GND") } -fn prefix(des: &str) -> String { des.chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_ascii_uppercase() }--/// The review, from the parts (read_sheet_file components: designator, pins with number/name/electrical) and the nets-/// ({net: ["U1.8", ...]}). Pure.-pub fn review(parts: &[Value], nets: &Map<String, Value>) -> Value {- // pin -> net- let mut net_of: BTreeMap<String, String> = BTreeMap::new();- for (n, ps) in nets { for p in ps.as_array().cloned().unwrap_or_default() { if let Some(s) = p.as_str() { net_of.insert(s.to_ascii_uppercase(), n.clone()); } } }- // every placed pin, once (a multi-part chip appears once per part on the sheets)- let mut pins: BTreeMap<String, (String, String, String, String)> = BTreeMap::new(); // key -> (designator, number, name, type)- for c in parts {- let des = c["designator"].as_str().unwrap_or("").to_string();- if des.is_empty() || des.contains('?') { continue; }- for p in c["pins"].as_array().cloned().unwrap_or_default() {- let num = p["number"].as_str().unwrap_or("").to_string();- pins.entry(format!("{des}.{num}").to_ascii_uppercase()).or_insert((des.clone(), num, p["name"].as_str().unwrap_or("").to_string(), pin_type(&p["electrical"])));- }- }- let nc = |name: &str| { let n = name.to_ascii_uppercase(); n == "NC" || n == "N/C" || n == "DNC" || n.starts_with("NC_") || n == "NO CONNECT" };- let mut errors = Vec::new();- let mut warnings = Vec::new();- for (key, (des, num, name, ty)) in &pins {- if net_of.contains_key(key) || nc(name) || ty == "not_connected" { continue; }- let f = json!({"check": "unconnected_pin", "pin": format!("{des}.{num}"), "name": name, "type": ty});- if ty == "power" { errors.push(f) } else { warnings.push(f) }- }- for (n, ps) in nets {- let members = ps.as_array().map(|a| a.len()).unwrap_or(0);- if members == 1 { warnings.push(json!({"check": "single_pin_net", "net": n, "pin": ps[0]})); }- let kinds: Vec<&str> = ps.as_array().cloned().unwrap_or_default().iter().filter_map(|p| p.as_str()).filter_map(|p| pins.get(&p.to_ascii_uppercase())).map(|t| t.3.as_str()).collect();- let outs = kinds.iter().filter(|k| **k == "output").count();- if outs >= 2 { errors.push(json!({"check": "outputs_together", "net": n, "outputs": outs})); }- let driven = kinds.iter().any(|k| matches!(*k, "output" | "io" | "power" | "supply" | "passive" | "open_collector" | "open_emitter" | "hiz" | "unknown"));- if !kinds.is_empty() && kinds.iter().all(|k| *k == "input") && !driven && members > 0 {- warnings.push(json!({"check": "undriven_input", "net": n, "inputs": kinds.len()}));- }- }- // decoupling: each IC power pin on a supply net (not ground) wants a capacitor between that net and a ground- let caps_between: BTreeMap<String, Vec<String>> = {- let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();- let mut cap_nets: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();- for (key, (des, ..)) in &pins {- if prefix(des) == "C" { if let Some(n) = net_of.get(key) { cap_nets.entry(des.clone()).or_default().insert(n.clone()); } }- }- for (c, ns) in cap_nets {- if ns.iter().any(|n| is_ground(n)) { for n in ns.iter().filter(|n| !is_ground(n)) { m.entry(n.clone()).or_default().push(c.clone()); } }- }- m- };- let mut supplies: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();- for (key, (des, _, _, ty)) in &pins {- if ty != "power" || !matches!(prefix(des).as_str(), "U" | "IC") { continue; }- if let Some(n) = net_of.get(key).filter(|n| !is_ground(n)) { supplies.entry(n.clone()).or_default().insert(des.clone()); }- }- let mut decoupling = Vec::new();- for (net, ics) in &supplies {- let caps = caps_between.get(net).cloned().unwrap_or_default();- // an inductor on a 'supply' pin's net makes it a switch node (a regulator's SW/LX pin): no capacitor belongs- // there (the Bluetooth Sentinel's SMPS_LX read as missing decoupling)- let switch = nets.get(net).and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| p.as_str()).any(|p| prefix(p.split('.').next().unwrap_or("")) == "L")).unwrap_or(false);- let row = json!({"net": net, "ics": ics, "capacitors": caps, "ok": !caps.is_empty() || switch, "switchNode": switch});- if caps.is_empty() && !switch { warnings.push(json!({"check": "no_decoupling", "net": net, "ics": ics})); }- decoupling.push(row);- }- json!({"pins": pins.len(), "nets": nets.len(), "errors": errors, "warnings": warnings, "decoupling": decoupling, "ok": errors.is_empty()})-}- /// altium_schematic_review {projectPath} pub fn schematic_review(args: &Value) -> Value { if let Some(g) = crate::support::need_licensed() { return g; }@@ -118,13 +30,13 @@ pub fn schematic_review(args: &Value) -> Value { } let n = crate::hier::netlist(&json!({"projectPath": prj})); if n.get("success").and_then(|b| b.as_bool()) != Some(true) { return n; }- let nets = n["nets"].as_object().cloned().unwrap_or_default();- let mut out = review(&parts, &nets);- out["success"] = json!(true);+ // the standard's review (adom-eda-checks schematic_review): the pin checks, decoupling, and the design checks+ // (floating reset or enable, I2C pull-ups, LED resistors, regulator capacitors) that read each part's value and libRef+ let mut out = adom_eda_checks::schreview::schematic_review(&json!({"sheetParts": parts, "netlist": {"nets": n["nets"], "names": n.get("names").cloned().unwrap_or(Value::Null)}}));+ if out.get("success").and_then(|b| b.as_bool()) != Some(true) { return out; } out["sheets"] = json!(sheets); out["unreadSheets"] = json!(unread); out["compileErrors"] = n["compileErrors"].clone();- out["_hint"] = json!("errors stop a board (a power pin on no net, two outputs on one net); warnings deserve a look (pins on no net, one-pin nets, inputs nothing drives, an IC supply with no capacitor to ground). Pin types come from the symbols: a passive pin is never 'undriven'. Fix on the sheets (altium_sch_connect, altium_sch_place_part), then altium_update_pcb."); out } @@ -193,14 +105,14 @@ mod tests { #[test] fn pin_types_come_as_codes_or_names() {- assert_eq!(pin_type(&json!(7)), "power");- assert_eq!(pin_type(&json!("Bidirectional")), "io");- assert_eq!(pin_type(&json!("sup")), "supply");+ assert_eq!(adom_eda_checks::schreview::pin_type(&json!(7)), "power");+ assert_eq!(adom_eda_checks::schreview::pin_type(&json!("Bidirectional")), "io");+ assert_eq!(adom_eda_checks::schreview::pin_type(&json!("sup")), "supply"); let parts = vec![json!({"designator": "U1", "pins": [ {"number": "1", "name": "IN", "electrical": "input"}, {"number": "2", "name": "X", "electrical": "not_connected"}]}), json!({"designator": "P1", "pins": [{"number": "1", "name": "VCC", "electrical": "supply"}]})]; let nets = json!({"VCC": ["U1.1", "P1.1"]});- let r = review(&parts, nets.as_object().unwrap());+ let r = adom_eda_checks::schreview::review(&parts, nets.as_object().unwrap()); assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}"); } @@ -214,7 +126,7 @@ mod tests { part("U3", &[("1", "SW", 7)]), part("L1", &[("1", "", 4), ("2", "", 4)]), ]; let nets = json!({"3V3": ["U1.1", "C1.1"], "VDD": ["U2.1"], "LX": ["U3.1", "L1.1"], "GND": ["U1.2", "U2.2", "C1.2"], "BUS": ["U1.3", "U2.3"], "SENSE": ["U2.4"], "R": ["R1.1", "R1.2"]});- let r = review(&parts, nets.as_object().unwrap());+ let r = adom_eda_checks::schreview::review(&parts, nets.as_object().unwrap()); let checks = |k: &str| r[k].as_array().unwrap().iter().map(|f| f["check"].as_str().unwrap().to_string()).collect::<Vec<_>>(); // U1.5 EN floats (input, warning); NC is skipped; two outputs share BUS (error) assert!(checks("errors").contains(&"outputs_together".to_string()));
bridge-rs/src/verbs.rs+13−1@@ -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", "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", "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",@@ -447,6 +447,16 @@ 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("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,+ "A part placed in op 0 can be wired in op 1. A failing op takes the batch back (errorCode op_failed, restored true); if Undo cannot bring the sheet back, errorCode partial says which ops ran. The sheet is left unsaved: altium_save keeps it.",+ &["sch_place_part", "sch_connect_pins", "build_schematic", "run_erc", "save"], &["Altium edits the open sheet: the batch is one Undo step per op, not one for the whole batch.", "An op naming another sheet is refused: a batch edits one sheet."], json!({"filePath": "C:/proj/Main.SchDoc", "ops": [{"op": "sch_place_part", "libReference": "RES", "designator": "R9", "at": [100, 80]}, {"op": "sch_connect_pins", "pairs": [{"from": "R9.1", "to": "U1.3"}]}]})),+ verb_doc("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.",+ json!({"sinceOffset": "int, default 0: where the last call stopped (its next)", "maxBytes": "int, default 200000", "errorsOnly": "bool: only errors and warnings"}),+ json!({"entries": "[{level: error | warning | info, text, source: messages | <log file>, class?, document?, at}] oldest first", "next": "the offset to pass next time", "truncated": "bool", "sources": "{messagesPanel, logFiles, captured}"}), 60,+ "Carry next from call to call. The panel empties on every compile, so each call captures what is new into the bridge's own file and offsets are bytes of that file: they stay valid across compiles and restarts.",+ &["dialog_log", "compile", "run_drc", "diagnostics"], &["The Messages panel is read only while the agent is resident; with Altium closed only its log files are read.", "Dialogs the bridge answered are in altium_dialog_log, not here."], json!({"sinceOffset": 0, "errorsOnly": true})), verb_doc("verb_times", "Measured run times of this bridge's verbs on this machine: per verb the count, p50, p90, max, last and failures, from its own run log, slowest p90 first.", json!({"limit": "int, default 40: how many verbs"}), json!({"verbs": "[{verb, count, p50Sec, p90Sec, maxSec, lastSec, failures}]", "since": "Unix seconds: when the log starts", "log": "the log file"}), 15,@@ -2214,6 +2224,8 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "verb_times" => progress::verb_times(args), "prewarm" => misc::prewarm(args), "render_board" => crate::render::render_board(args),+ "log_tail" => crate::logtail::log_tail(args),+ "sch_batch" => crate::schbatch::sch_batch(args), "symbol_mode" => library::symbol_mode(args), "cleanup_libs" => library::cleanup_libs(args), "install_library" => library::install_library(args),
bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-eda-checks"-version = "0.21.1"+version = "0.22.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−2@@ -31,12 +31,12 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives. | `length_tune` | board, rules? | a serpentine on the net's longest straight track with room beside it, its bumps sized to add exactly what `targetMm` (or `matchTo`, another net's length) asks, every bump `clearance` (the board's strictest rule) from other nets' pads, routed tracks and vias and inside the board; answered as the track to `remove` and the `routeNet` that replaces it. From the Altium bridge's lengthtune.rs | | `lint_library` | library | is a symbol or footprint library fit to ship (standard #28): the shared rules with a fixed severity each (`no_pads`, `zero_size_pad`, `duplicate_pad_number`, `no_courtyard`, `origin_off_part`, `pin_without_pad`, `pad_without_pin`, `no_part_number`, ...; `rules` in the reply lists them), checked from the footprints and symbols the bridge sends; a key left out is not checked, a key sent empty is a finding; the bridge's own findings (`tool_refuses_file`) pass through | | `net_lengths` | board | the routed length of each net (tracks and arcs, by layer, with its vias), the skew of each differential pair (`pairs`, else found by net name: `_P`/`_N`, `+`/`-`) and the spread of each matched-length group against its tolerance (`groups`). From the Altium bridge's lengths.rs |-| `placement_check` | board, bodies? | courtyard overlaps (pads and bodies, grown by `marginMm`), parts off or over the edge, pads within `edgeMm` of the edge, parts on mounting holes; `stacked` lists plan-view overlaps where one part sits wholly above the other (a part under a raised molecule: pads apart, no bodies meeting in 3D); `bodiesUsed: false` when no bodies were given |+| `placement_check` | board, bodies? | courtyard overlaps (pads and bodies, grown by `marginMm`), parts off or over the edge, pads within `edgeMm` of the edge, parts on mounting holes; `stacked` lists plan-view overlaps where one part sits wholly above the other (a part under a raised molecule: pads apart, no bodies meeting in 3D); `bodiesUsed: false` when no bodies were given; plus a 0-100 score and grade (from kicad-bridge's score_placement): connectors farther than `connectorEdgeMm` from the edge, decoupling capacitors farther than `decouplingMm` from their IC's pin on the same rail, and the ratsnest's length against the board diagonal | | `plan_fanout` | board, stack?, rules? | the fanout of a BGA or QFN/QFP (`ref`): pitch and package from its pads; a BGA's outer ring escapes on the surface and each inner ball takes a dogbone via, or a via in the pad when the dogbone does not fit (`style` auto); a perimeter pad takes an outward stub, with a via at its end for ground or `viaPerimeter`, and an exposed pad a via grid. `calls` are route_net arguments, one per net; `conflicts` lists each via and stub closer than the clearance to another net's pad, track, arc or via anywhere on the board. A pin its net's copper already reaches is skipped (`includeRouted` plans it anyway), the exposed-pad grid keeps clear of holes already there, and `crossesPours` names other nets' pours the plan runs into (repour before DRC). From the KiCad bridge's place_tools | | `plan_route` | board, rules? | a path between two pads of a net (`from`, `to` as Ref.Pad) on any listed copper `layers`, with through vias between them: a bounded orthogonal A* on `gridMm`, width and via from the args, else the board's width and via rules (`planner.widthFrom`, `viaFrom`), keeping `widthMm/2` + the board's strictest board-wide copper clearance rule from other nets' copper (pads by their real outline), inside the outline, no via in a pad; a through via is checked on every copper layer of the board (`planner.viasCheckedOn`), not only the planned ones. `routeNet` is route_net's arguments, unchanged. Pours are not obstacles (repour after), but `crossesPours` names each other net's pour the route runs through, since that can split it; `avoidPours: true` keeps the route out of them (or a list of nets: out of theirs only), and `pourCost` makes a mm inside one cost 1 + pourCost mm, a preference where a hard block finds no path; a pour that holds the route's own end pad is exempt and named (`planner.avoidExempt`); with no path, `ends` names the avoided pours at each end pad and whether they are exempt, and `withoutAvoid` says whether a path exists through them. The grid path is smoothed to straight and 45-degree segments where they keep the same clearance (`smooth: false` keeps it) | | `review_board` | board, sheetParts?, rules? | small design-review checks, errors first: placeholder values, single-pin nets, duplicate designators, parts with pads off the outline polygon or near the edge (`edgeMm`), parts with no footprint name, off-grid parts (with `gridMm`); from the sheet parts, missing Mouser/DigiKey/LCSC numbers and datasheets and placeholder comments; from the rules, disabled ones, missing clearance/width/hole-size/short-circuit rules and same-priority ties (rules classed from a standard kind, a descriptor, Altium's ordinal or the rule's own name; `alwaysChecked` names classes a tool always checks, like EAGLE's shorts). `skipped` and `notImplemented` say what was not judged. From the Altium bridge's review.rs | | `route_pair` | board, stack?, rules? | a differential pair planned as one centreline (pad midpoints through `via` waypoints) with each net offset half a pitch to its own side, mitred corners and a `fanMm` fan-out; width and gap given, or from `diffOhms` and the stack. `problems` names a crossing or other copper (pads by outline, routed tracks, vias) closer than the clearance; `routeNet` holds both nets' route_net arguments and `widthRule` the pair's add_rule. From the Altium bridge's pairroute.rs |-| `schematic_review` | sheetParts, netlist | every placed pin, with its electrical type, against the compiled netlist: power pins on no net and outputs driving each other (errors); unconnected pins, one-pin nets, inputs nothing drives and IC supplies with no capacitor to ground (warnings; a regulator's switch node on an inductor is no missing capacitor). From the Altium bridge's schreview.rs |+| `schematic_review` | sheetParts, netlist | every placed pin, with its electrical type, against the compiled netlist: power pins on no net and outputs driving each other (errors); unconnected pins, one-pin nets, inputs nothing drives and IC supplies with no capacitor to ground (warnings; a regulator's switch node on an inductor is no missing capacitor). From the Altium bridge's schreview.rs; plus the design checks from kicad-bridge's design_review and sch_check: I2C lines with no pull-up, reset and enable pins floating or with nothing setting their level, LEDs with no series resistor, regulators missing input or output capacitors, rails with no bulk capacitor, unannotated or doubled designators, no-connect flags on wired pins, and two names on one net (`netlist.names`); each with `message` and `fix` | | `silk_designators` | board, silk | a place for each reference designator: one size (`size`, stepping down to `minSize`), beside its own part, clear of every pad by `padClearance`, of other parts' bodies and of other labels, inside the board. `applyArgs` is apply_silkscreen's arguments; parts with no clear spot are listed, not forced. From the Altium bridge's silkplace.rs | | `teardrops` | board, rules? | a tapered fill where a track meets a via or pad of its own net (`targets` via, tht, smd), as wide as the pad at its centre (`widthRatio`) and narrowing to the track `lengthRatio` x the pad's size past its edge; each a polygon on the track's layer kept clear of other nets' copper by the board's clearance, the joints with no room skipped and named | | `thermal_vias` | board, rules? | a grid of vias in a part's exposed pad (`ref`, `pad?`), clear of vias already there; `apply` is `place_vias` arguments |
bridge-rs/vendor/adom-eda-checks/src/placement.rs+114−3@@ -1,6 +1,8 @@ //! A placement review before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same //! side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a-//! mounting hole. From the Altium bridge's placement.rs.+//! mounting hole. From the Altium bridge's placement.rs. The score after it (connectors away from the edge, decoupling+//! capacitors far from their IC, the ratsnest's length, and a 0-100 grade) is ported from kicad-bridge's+//! score_placement (#29). use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -115,7 +117,93 @@ pub fn is_stacked(pads: &[Value], bs: &[crate::bodies::BodyBox], a: &str, b: &st !ba.iter().any(|p| bb.iter().any(|q| { let (h, d) = crate::bodies::xy_meet(p, q); (h || d < 2.0 * margin) && p.z0.max(q.z0) < p.z1.min(q.z1) })) } -/// placement_check: input {board, bodies?, args: {marginMm?, edgeMm?}}. Without bodies the parts' boxes are their pads+fn prefix(r: &str) -> String { r.chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_ascii_uppercase() }++/// A connector by designator or footprint name. X is not enough on its own: Altium designs name crystals X1 (the+/// Sentinel's 16 MHz and 32.768 kHz read as connectors far from the edge).+fn is_connector(r: &str, pattern: &str) -> bool {+ let lib = pattern.to_ascii_lowercase();+ matches!(prefix(r).as_str(), "J" | "P" | "CN" | "USB" | "CON") || ["connector", "usb", "pinheader", "pin_header", "terminalblock", "jst", "molex", "barrel"].iter().any(|k| lib.contains(k))+}++/// The score: deductions per rule (per item, capped), the ratsnest's share of the board diagonal, 0-100 and a grade.+/// `overlaps` and `off` are counts from the review. Pure.+pub fn score(st: &Value, boxes: &BTreeMap<String, (bool, Rect)>, ring: &[(f64, f64)], overlaps: usize, off: usize, connector_edge: f64, decoupling: f64) -> Value {+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let (bx0, bx1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));+ let (by0, by1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));+ let pattern: BTreeMap<String, String> = st["components"].as_array().cloned().unwrap_or_default().iter()+ .filter_map(|c| Some((c["ref"].as_str()?.to_string(), c["pattern"].as_str().unwrap_or("").to_string()))).collect();+ // connectors farther than connectorEdgeMm from the board's edge (its box)+ let mut far_conn = Vec::new();+ for (r, (_, b)) in boxes {+ if !is_connector(r, pattern.get(r).map(|s| s.as_str()).unwrap_or("")) { continue; }+ let d = (b.0 - bx0).min(bx1 - b.2).min(b.1 - by0).min(by1 - b.3);+ if d < 0.0 { continue; } // off or over the edge: the review has it+ if d > connector_edge { far_conn.push(json!({"ref": r, "edgeDistanceMm": r3(d)})); }+ }+ // decoupling capacitors (two pads: one on a ground, one on a supply rail an IC also has) farther than decouplingMm+ // from that IC's nearest pin on the same net. The net must look like a rail: a crystal's load capacitor (the+ // Sentinel's C1 on 16M_IN) is a signal to ground, not decoupling.+ let net = |p: &Value| p["net"].as_str().unwrap_or("").to_string();+ let mut by_ref: BTreeMap<String, Vec<&Value>> = BTreeMap::new();+ for p in &pads { if let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) { by_ref.entry(r.to_string()).or_default().push(p); } }+ let is_ic = |r: &str| matches!(prefix(r).as_str(), "U" | "IC") && by_ref.get(r).map(|v| v.len() >= 3).unwrap_or(false);+ let mut far_caps = Vec::new();+ for (r, ps) in &by_ref {+ if prefix(r) != "C" || ps.len() != 2 { continue; }+ let g = ps.iter().filter(|p| crate::schreview::is_ground(&net(p))).count();+ let Some(pw) = ps.iter().find(|p| !net(p).is_empty() && !crate::schreview::is_ground(&net(p))) else { continue };+ if g != 1 || !crate::schreview::looks_like_rail(&net(pw)) { continue; }+ let n = net(pw);+ let best = pads.iter().filter(|q| net(q) == n && q["ref"].as_str().map(|x| x != r && is_ic(x)).unwrap_or(false))+ .map(|q| (((f(&q["x"]) - f(&pw["x"])).powi(2) + (f(&q["y"]) - f(&pw["y"])).powi(2)).sqrt(), q)).min_by(|a, b| a.0.total_cmp(&b.0));+ if let Some((d, q)) = best { if d > decoupling { far_caps.push(json!({"ref": r, "net": n, "nearestPin": format!("{}.{}", q["ref"].as_str().unwrap_or(""), q["name"].as_str().unwrap_or("")), "distanceMm": r3(d)})); } }+ }+ // the ratsnest: each net's minimum spanning tree over its pads' centres+ let mut nets: BTreeMap<String, Vec<(f64, f64)>> = BTreeMap::new();+ for p in &pads { let n = net(p); if !n.is_empty() { nets.entry(n).or_default().push((f(&p["x"]), f(&p["y"]))); } }+ let (mut mst, mut edges) = (0.0, 0usize);+ for pts in nets.values().filter(|v| v.len() > 1) {+ let mut best = vec![f64::MAX; pts.len()];+ let mut done = vec![false; pts.len()];+ best[0] = 0.0;+ for _ in 0..pts.len() {+ let Some(i) = (0..pts.len()).filter(|&i| !done[i]).min_by(|&a, &b| best[a].total_cmp(&best[b])) else { break };+ done[i] = true;+ mst += best[i];+ for j in 0..pts.len() { if !done[j] { let d = ((pts[i].0 - pts[j].0).powi(2) + (pts[i].1 - pts[j].1).powi(2)).sqrt(); if d < best[j] { best[j] = d; } } }+ }+ edges += pts.len() - 1;+ }+ let diag = ((bx1 - bx0).powi(2) + (by1 - by0).powi(2)).sqrt();+ let frac = if edges > 0 && diag > 0.0 { mst / edges as f64 / diag } else { 0.0 };+ let mut deductions = Vec::new();+ let mut total = 0.0;+ let mut push = |rule: &str, per: f64, cap: f64, items: Vec<Value>, detail: &str| {+ let pts = (per * items.len() as f64).min(cap);+ total += pts;+ deductions.push(json!({"rule": rule, "count": items.len(), "points": pts, "perItem": per, "cap": cap, "items": items, "detail": detail}));+ };+ push("courtyard_overlap", 10.0, 40.0, (0..overlaps).map(|_| json!(null)).collect(), "same-side parts that overlap (courtyardOverlaps)");+ push("outside_board", 10.0, 30.0, (0..off).map(|_| json!(null)).collect(), "parts off or over the board edge (offOrOverEdge)");+ push("connector_off_edge", 5.0, 15.0, far_conn.clone(), "connectors farther than connectorEdgeMm from the board edge");+ push("decoupling_far", 3.0, 15.0, far_caps.clone(), "decoupling capacitors farther than decouplingMm from their IC's nearest pin on the same supply");+ let rpts = (((frac - 0.1) / 0.3).clamp(0.0, 1.0) * 200.0).round() / 10.0;+ total += rpts;+ let mean = if edges > 0 { mst / edges as f64 } else { 0.0 };+ deductions.push(json!({"rule": "ratsnest_length", "count": edges, "points": rpts, "cap": 20.0, "items": [],+ "detail": format!("mean ratsnest edge {:.2} mm is {:.1} % of the {:.1} mm board diagonal (0 points at 10 %, 20 at 40 %)", mean, frac * 100.0, diag)}));+ // the overlap and outside items are listed in the review itself+ for d in deductions.iter_mut() { if d["items"].as_array().map(|a| a.iter().all(|x| x.is_null())).unwrap_or(false) { d["items"] = json!([]); } }+ deductions.sort_by(|a, b| b["points"].as_f64().unwrap_or(0.0).total_cmp(&a["points"].as_f64().unwrap_or(0.0)));+ let score = (100.0 - total).max(0.0).round();+ let grade = match score as i64 { 90..=100 => "A", 80..=89 => "B", 70..=79 => "C", 50..=69 => "D", _ => "F" };+ json!({"score": score, "grade": grade, "deductions": deductions, "connectorsOffEdge": far_conn, "decouplingFar": far_caps,+ "ratsnest": {"totalMm": r3(mst), "edges": edges, "meanMm": r3(mean), "boardDiagonalMm": r3(diag), "share": r3(frac)}})+}++/// placement_check: input {board, bodies?, args: {marginMm?, edgeMm?, connectorEdgeMm? (3), decouplingMm? (3)}}. Without bodies the parts' boxes are their pads /// only, and the reply says so (`bodiesUsed: false`). pub fn placement_check(input: &Value) -> Value { let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };@@ -151,9 +239,11 @@ pub fn placement_check(input: &Value) -> Value { out["courtyardOverlaps"] = json!(real); out["stacked"] = json!(stacked); }+ let sc = score(&st, &boxes, &ring, out["courtyardOverlaps"].as_array().map(|a| a.len()).unwrap_or(0), out["offOrOverEdge"].as_array().map(|a| a.len()).unwrap_or(0), num("connectorEdgeMm", 3.0), num("decouplingMm", 3.0));+ for k in ["score", "grade", "deductions", "connectorsOffEdge", "decouplingFar", "ratsnest"] { out[k] = sc[k].clone(); } out["success"] = json!(true); out["bodiesUsed"] = json!(given.is_some());- out["_hint"] = json!("courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (move_parts, find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part. Without bodies (bodiesUsed false) a part's box is its pads only: pass the bodies companion to count overhanging bodies.");+ out["_hint"] = json!("courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (move_parts, find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part. Without bodies (bodiesUsed false) a part's box is its pads only: pass the bodies companion to count overhanging bodies. score (0-100, grade A-F) weighs these with connectorsOffEdge (a connector deep inside the board), decouplingFar (a capacitor far from its IC's supply pin: place_decoupling) and the ratsnest's length; ok counts only overlaps, off-board parts and parts on holes."); out } @@ -183,6 +273,27 @@ mod tests { assert_eq!(r["ok"], json!(false)); } + #[test]+ fn the_score_finds_a_deep_connector_and_a_far_capacitor() {+ let pad = |r: &str, n: &str, x: f64, y: f64, net: &str| json!({"ref": r, "name": n, "x": x, "y": y, "sizeX": 1.0, "sizeY": 1.0, "rotation": 0.0, "net": net});+ // a 50 x 30 board: J1 in the middle, C1 10 mm from U1's VDD pin, C2 beside it+ let st = json!({"outline": [[0, 0], [50, 0], [50, 30], [0, 30]],+ "outlineEdges": [{"kind": "line", "start": [0.0, 0.0]}, {"kind": "line", "start": [50.0, 0.0]}, {"kind": "line", "start": [50.0, 30.0]}, {"kind": "line", "start": [0.0, 30.0]}],+ "components": [{"ref": "J1", "side": "top", "pattern": "PinHeader_1x02"}, {"ref": "U1", "side": "top"}, {"ref": "C1", "side": "top"}, {"ref": "C2", "side": "top"}],+ "pads": [pad("J1", "1", 25.0, 15.0, "SIG"), pad("J1", "2", 27.0, 15.0, "GND"),+ pad("U1", "VDD", 10.0, 10.0, "+3V3"), pad("U1", "GND", 10.0, 12.0, "GND"), pad("U1", "IO", 12.0, 10.0, "SIG"),+ pad("C1", "1", 20.0, 10.0, "+3V3"), pad("C1", "2", 21.0, 10.0, "GND"),+ pad("C2", "1", 10.0, 8.0, "+3V3"), pad("C2", "2", 11.0, 8.0, "GND")]});+ let r = placement_check(&json!({"board": st, "args": {}}));+ assert_eq!(r["connectorsOffEdge"][0]["ref"], "J1", "{r}");+ let far: Vec<&str> = r["decouplingFar"].as_array().unwrap().iter().map(|c| c["ref"].as_str().unwrap()).collect();+ assert_eq!(far, vec!["C1"]);+ assert_eq!(r["decouplingFar"][0]["nearestPin"], "U1.VDD");+ assert!(r["score"].as_f64().unwrap() < 100.0 && r["grade"].is_string());+ assert_eq!(r["ok"], json!(true), "a score is advice: ok counts only overlaps, off-board parts and holes");+ assert!(r["ratsnest"]["edges"].as_u64().unwrap() > 0);+ }+ #[test] fn a_part_under_a_raised_one_is_stacked_not_overlapping() { let pad = |r: &str, x: f64, y: f64| json!({"ref": r, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6, "rotation": 0.0});
bridge-rs/vendor/adom-eda-checks/src/schreview.rs+299−7@@ -1,6 +1,8 @@ //! A schematic review before the board is updated: every placed pin from the sheets (with its electrical type) against //! the compiled netlist, and the symbols' pins against the footprints' pads. From the Altium bridge's schreview.rs. Unconnected pins (power pins as errors), nets with one pin, outputs driving each-//! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground.+//! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground. The design checks after it+//! (I2C pull-ups, reset and enable pins, LED resistors, regulator and bulk capacitors, annotation, no-connect flags on+//! wired pins, two names on one net) are ported from kicad-bridge's design_review and sch_check (#29). use serde_json::{json, Map, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -24,6 +26,12 @@ pub fn pin_type(v: &Value) -> String { "tri" | "tristate" | "3state" => "hiz".into(), "in" => "input".into(), "out" => "output".into(),+ // KiCad's names+ "power_in" => "power".into(),+ "power_out" => "supply".into(),+ "tri_state" => "hiz".into(),+ "no_connect" | "unconnected" => "not_connected".into(),+ "unspecified" | "free" => "unknown".into(), o => o.to_string(), }, _ => "unknown".into(),@@ -59,8 +67,13 @@ pub fn review(parts: &[Value], nets: &Map<String, Value>) -> Value { let nc = |name: &str| { let n = name.to_ascii_uppercase(); n == "NC" || n == "N/C" || n == "DNC" || n.starts_with("NC_") || n == "NO CONNECT" }; let mut errors = Vec::new(); let mut warnings = Vec::new();+ let mut infos = Vec::new();+ let found = design_checks(parts, nets, &pins, &net_of);+ // a reset or enable pin reported floating is not reported again as an unconnected pin+ let floating: BTreeSet<String> = found.iter().filter(|(_, f)| f["check"] == "reset_enable" && f["floating"] == true).filter_map(|(_, f)| f["pin"].as_str().map(|s| s.to_ascii_uppercase())).collect();+ for (sev, f) in found { match sev { "error" => errors.push(f), "warning" => warnings.push(f), _ => infos.push(f) } } for (key, (des, num, name, ty)) in &pins {- if net_of.contains_key(key) || nc(name) || ty == "not_connected" { continue; }+ if net_of.contains_key(key) || nc(name) || ty == "not_connected" || floating.contains(key) { continue; } let f = json!({"check": "unconnected_pin", "pin": format!("{des}.{num}"), "name": name, "type": ty}); if ty == "power" { errors.push(f) } else { warnings.push(f) } }@@ -102,7 +115,225 @@ pub fn review(parts: &[Value], nets: &Map<String, Value>) -> Value { if caps.is_empty() && !switch { warnings.push(json!({"check": "no_decoupling", "net": net, "ics": ics})); } decoupling.push(row); }- json!({"pins": pins.len(), "nets": nets.len(), "errors": errors, "warnings": warnings, "decoupling": decoupling, "ok": errors.is_empty()})+ json!({"pins": pins.len(), "nets": nets.len(), "errors": errors, "warnings": warnings, "infos": infos, "decoupling": decoupling, "ok": errors.is_empty()})+}++/// A net name's last segment, upper case (KiCad's hierarchical "/sheet/SDA" reads as SDA).+fn tail(net: &str) -> String { net.rsplit('/').next().unwrap_or(net).to_ascii_uppercase() }++/// A supply rail by its name: +3V3, VCC, VDD..., 5V, 3V3, 1V8.+pub fn looks_like_rail(net: &str) -> bool {+ let n = tail(net);+ if n.starts_with('+') || (n.starts_with('-') && n.chars().nth(1).map_or(false, |c| c.is_ascii_digit())) { return true; }+ if ["VCC", "VDD", "VBUS", "VBAT", "VIN", "VSYS", "VREF", "VIO", "VAA", "AVDD", "DVDD", "IOVDD", "VMOT", "VOUT", "VREG"].iter().any(|p| n.starts_with(p)) { return true; }+ let core = n.trim_start_matches('V');+ let digits = core.chars().take_while(|c| c.is_ascii_digit()).count();+ digits > 0 && core.chars().nth(digits) == Some('V')+}++/// A pin name without overbar markup and separators: `~{RESET}` and `/RESET` read RESET.+pub fn norm_pin(name: &str) -> String { name.replace("~{", "").replace(['}', '~', '/', '#', ' '], "").to_ascii_uppercase() }++/// Farads from a value like 100n, 4.7uF, 10µ, 1u0 or 22pF; None when unreadable (a bare number has no unit).+pub fn farads(v: &str) -> Option<f64> {+ let s = v.trim().replace(['µ', 'μ'], "u").to_ascii_lowercase();+ let s = s.split([' ', '/', ',']).next().unwrap_or("").trim_end_matches('f').to_string();+ let (mut num, mut mult, mut unit) = (String::new(), 1.0, false);+ for c in s.chars() {+ if c.is_ascii_digit() || c == '.' { num.push(c); }+ else if !unit {+ mult = match c { 'p' => 1e-12, 'n' => 1e-9, 'u' => 1e-6, 'm' => 1e-3, _ => return None };+ if !num.contains('.') { num.push('.'); }+ unit = true;+ } else { return None; }+ }+ if !unit { return None; }+ num.trim_end_matches('.').parse::<f64>().ok().map(|x| x * mult)+}++fn fmt_farads(f: f64) -> String {+ let (v, u) = if f >= 1e-6 { (f / 1e-6, "u") } else if f >= 1e-9 { (f / 1e-9, "n") } else { (f / 1e-12, "p") };+ format!("{}{u}", ((v * 1000.0).round() / 1000.0))+}++#[derive(Clone, Copy, PartialEq)]+enum Kind { Capacitor, Resistor, Led, Regulator, Ic, Connector, Other }++/// One part with every unit's pins merged: (designator, library id, value, [(number, name, type)]).+struct Part { des: String, lib: String, value: String, pins: Vec<(String, String, String)> }++fn kind(p: &Part) -> Kind {+ let pre = prefix(&p.des);+ let lib = p.lib.to_ascii_lowercase();+ let sym = lib.rsplit(':').next().unwrap_or(&lib).to_string();+ let val = p.value.to_ascii_lowercase();+ if (lib.contains("led") && (pre == "D" || pre == "LED")) || sym.starts_with("led") || pre == "LED" { return Kind::Led; }+ if pre == "C" || sym == "c" || sym.starts_with("c_") || sym == "cp" || sym.starts_with("cp_") { return Kind::Capacitor; }+ if pre == "R" || sym == "r" || sym.starts_with("r_") { return Kind::Resistor; }+ if matches!(pre.as_str(), "J" | "P" | "CN") || lib.starts_with("connector") { return Kind::Connector; }+ if lib.starts_with("regulator_") || lib.contains("regulator") || val.contains("ldo") || val.contains("1117") { return Kind::Regulator; }+ if pre == "U" || pre == "IC" {+ let has_in = p.pins.iter().any(|x| matches!(norm_pin(&x.1).as_str(), "VIN" | "VI" | "IN"));+ let has_out = p.pins.iter().any(|x| matches!(norm_pin(&x.1).as_str(), "VOUT" | "VO" | "OUT") && x.2 == "supply");+ return if has_in && has_out { Kind::Regulator } else { Kind::Ic };+ }+ Kind::Other+}++/// The design checks: (severity, finding). Each finding carries check, refs, nets, message and fix. Pure.+fn design_checks(parts: &[Value], nets: &Map<String, Value>, pins: &BTreeMap<String, (String, String, String, String)>, net_of: &BTreeMap<String, String>) -> Vec<(&'static str, Value)> {+ let s = |v: &Value, k: &[&str]| k.iter().find_map(|k| v[*k].as_str().filter(|x| !x.is_empty())).unwrap_or("").to_string();+ // parts, units merged by designator+ let mut by: BTreeMap<String, Part> = BTreeMap::new();+ for (key, (des, num, name, ty)) in pins {+ let _ = key;+ let e = by.entry(des.clone()).or_insert_with(|| Part { des: des.clone(), lib: String::new(), value: String::new(), pins: Vec::new() });+ e.pins.push((num.clone(), name.clone(), ty.clone()));+ }+ for c in parts {+ let des = s(c, &["designator"]);+ if let Some(e) = by.get_mut(&des) {+ if e.lib.is_empty() { e.lib = s(c, &["libRef", "libId", "lib", "symbol", "library"]); }+ if e.value.is_empty() { e.value = s(c, &["value", "comment"]); }+ }+ }+ let kinds: BTreeMap<String, Kind> = by.values().map(|p| (p.des.clone(), kind(p))).collect();+ let net_pin = |des: &str, num: &str| net_of.get(&format!("{des}.{num}").to_ascii_uppercase()).cloned();+ let members = |net: &str| -> Vec<(String, String)> {+ nets.get(net).and_then(|a| a.as_array()).map(|a| a.iter().filter_map(|p| p.as_str()).filter_map(|p| p.rsplit_once('.').map(|(d, n)| (d.to_string(), n.to_string()))).collect()).unwrap_or_default()+ };+ let single = |net: &Option<String>| net.as_ref().map(|n| members(n).len() <= 1).unwrap_or(true);+ // two-terminal parts of a kind on a net: (designator, the net at its other end)+ let two_terminal = |net: &str, k: Kind| -> Vec<(String, String)> {+ by.values().filter(|p| kinds[&p.des] == k && p.pins.len() == 2).filter_map(|p| {+ let (a, b) = (net_pin(&p.des, &p.pins[0].0)?, net_pin(&p.des, &p.pins[1].0)?);+ if a == net { Some((p.des.clone(), b)) } else if b == net { Some((p.des.clone(), a)) } else { None }+ }).collect()+ };+ let caps_to_ground = |net: &str| -> Vec<(String, Option<f64>)> {+ two_terminal(net, Kind::Capacitor).into_iter().filter(|(_, o)| is_ground(o)).map(|(d, _)| { let v = farads(&by[&d].value); (d, v) }).collect()+ };+ let rails: BTreeSet<String> = nets.keys().filter(|n| !is_ground(n) && (looks_like_rail(n) || members(n).iter().any(|(d, k)| pins.get(&format!("{d}.{k}").to_ascii_uppercase()).map(|t| t.3 == "supply").unwrap_or(false)))).cloned().collect();+ let refs_on = |net: &str| -> Vec<String> { members(net).into_iter().map(|(d, _)| d).collect::<BTreeSet<_>>().into_iter().collect() };+ let mut out: Vec<(&'static str, Value)> = Vec::new();+ let mut add = |sev: &'static str, check: &str, refs: Vec<String>, nets: Vec<String>, message: String, fix: String, extra: Value| {+ let mut f = json!({"check": check, "refs": refs, "nets": nets, "message": message, "fix": fix});+ if let Some(o) = extra.as_object() { for (k, v) in o { f[k] = v.clone(); } }+ out.push((sev, f));+ };++ // i2c_pullups: an SDA or SCL line with no resistor to a supply rail+ for net in nets.keys() {+ let t = tail(net);+ let named = t.split(|c: char| !c.is_ascii_alphanumeric()).any(|x| x.starts_with("SDA") || x.starts_with("SCL"));+ let by_pin = members(net).iter().any(|(d, k)| pins.get(&format!("{d}.{k}").to_ascii_uppercase()).map(|t| matches!(norm_pin(&t.2).as_str(), "SDA" | "SCL" | "I2C_SDA" | "I2C_SCL")).unwrap_or(false));+ if !(named || by_pin) || members(net).len() <= 1 { continue; }+ if two_terminal(net, Kind::Resistor).iter().any(|(_, o)| rails.contains(o)) { continue; }+ add("warning", "i2c_pullups", refs_on(net), vec![net.clone()], format!("I2C line {net} has no pull-up resistor to a supply rail"),+ format!("I2C drivers only pull low: add a resistor from {net} to the I/O rail (4.7k for 100 kHz, 2.2k for 400 kHz), once per bus, unless the pull-up is on another board."), json!({}));+ }++ // reset_enable: a reset, enable or boot pin floating, or with nothing setting its level+ const NAMES: &[&str] = &["RESET", "RST", "NRST", "RESETN", "RSTN", "NRESET", "MCLR", "EN", "ENABLE", "CE", "CHIP_EN", "CHIPEN", "SHDN", "NSHDN", "SHDNN", "PWRDN", "ON", "ONOFF", "RUN"];+ for p in by.values().filter(|p| matches!(kinds[&p.des], Kind::Ic | Kind::Regulator)) {+ for (num, name, ty) in &p.pins {+ let n = norm_pin(name);+ if !(NAMES.contains(&n.as_str()) || n.starts_with("RESET") || n.starts_with("NRST") || n.starts_with("RST")) || matches!(ty.as_str(), "output" | "supply" | "not_connected") { continue; }+ let net = net_pin(&p.des, num);+ let pin = format!("{}.{num}", p.des);+ if single(&net) {+ add("error", "reset_enable", vec![p.des.clone()], net.iter().cloned().collect(), format!("{pin} {name} is floating"),+ format!("Tie {pin} to its active state (the supply for an enable that is always on, or a 10k pull-up with 100 nF to ground for a reset), or drive it from a GPIO."), json!({"pin": pin, "floating": true}));+ continue;+ }+ let net = net.unwrap();+ let defined = rails.contains(&net) || is_ground(&net) || members(&net).iter().any(|(d, k)| {+ let e = pins.get(&format!("{d}.{k}").to_ascii_uppercase()).map(|t| t.3.as_str()).unwrap_or("");+ (*d != p.des && matches!(e, "output" | "io" | "open_collector" | "open_emitter" | "supply" | "hiz")) || matches!(kinds.get(d), Some(Kind::Resistor) | Some(Kind::Connector))+ });+ if !defined {+ add("warning", "reset_enable", vec![p.des.clone()], vec![net.clone()], format!("Nothing sets the level of {pin} {name} (net {net})"),+ format!("Add a pull resistor on {net} to the inactive level, or drive it from a GPIO or a supervisor."), json!({"pin": pin}));+ }+ }+ }++ // led_resistor: an LED with no series resistor on either side+ for p in by.values().filter(|p| kinds[&p.des] == Kind::Led) {+ let pn: Vec<String> = p.pins.iter().filter_map(|x| net_pin(&p.des, &x.0)).collect();+ let limited = pn.iter().any(|n| members(n).iter().any(|(d, _)| *d != p.des && kinds.get(d) == Some(&Kind::Resistor)));+ if !limited {+ add("warning", "led_resistor", vec![p.des.clone()], pn, format!("LED {} has no series resistor on either side", p.des),+ format!("Put a resistor in series with {}: R = (Vsupply - Vf) / I, for example 330R to 1k at 3.3 V; skip it only if a constant-current driver feeds the LED.", p.des), json!({}));+ }+ }++ // regulator_caps: a regulator with no input or output capacitor, or too little on the output+ for p in by.values().filter(|p| kinds[&p.des] == Kind::Regulator) {+ let outs: BTreeSet<String> = p.pins.iter().filter(|x| x.2 == "supply" || matches!(norm_pin(&x.1).as_str(), "VOUT" | "VO" | "OUT")).filter_map(|x| net_pin(&p.des, &x.0)).collect();+ let ins: BTreeSet<String> = p.pins.iter().filter(|x| x.2 == "power" || matches!(norm_pin(&x.1).as_str(), "VIN" | "VI" | "IN")).filter_map(|x| net_pin(&p.des, &x.0)).filter(|n| !is_ground(n) && !outs.contains(n)).collect();+ for net in ins {+ if caps_to_ground(&net).is_empty() {+ add("warning", "regulator_caps", vec![p.des.clone()], vec![net.clone()], format!("Regulator {} has no input capacitor on {net}", p.des),+ format!("Add the input capacitor the datasheet asks for (typically 1 uF to 10 uF ceramic) from {net} to ground beside {}.", p.des), json!({}));+ }+ }+ for net in outs {+ let caps = caps_to_ground(&net);+ let biggest = caps.iter().filter_map(|c| c.1).fold(None, |a: Option<f64>, f| Some(a.map_or(f, |x| x.max(f))));+ if caps.is_empty() {+ add("warning", "regulator_caps", vec![p.des.clone()], vec![net.clone()], format!("Regulator {} has no output capacitor on {net}", p.des),+ format!("Most LDOs need a minimum output capacitance to be stable: add the datasheet's (typically 1 uF to 10 uF ceramic) from {net} to ground beside {}.", p.des), json!({}));+ } else if caps.iter().all(|c| c.1.is_some()) && biggest.map_or(false, |b| b < 0.99e-6) {+ add("warning", "regulator_caps", vec![p.des.clone()], vec![net.clone()], format!("Regulator {} output {net} has only {} of capacitance", p.des, fmt_farads(biggest.unwrap_or(0.0))),+ format!("Add a 1 uF to 10 uF ceramic from {net} to ground beside {} (check the datasheet's minimum and ESR range).", p.des), json!({}));+ }+ }+ }++ // bulk_capacitance: a rail feeding ICs with no capacitor of 4.7 uF or more+ for net in &rails {+ let loads = members(net).iter().filter(|(d, k)| matches!(kinds.get(d), Some(Kind::Ic) | Some(Kind::Regulator)) && pins.get(&format!("{d}.{k}").to_ascii_uppercase()).map(|t| t.3 == "power").unwrap_or(false)).count();+ if loads == 0 { continue; }+ let caps = caps_to_ground(net);+ if caps.iter().any(|c| c.1.map_or(true, |f| f >= 4.7e-6 * 0.99)) { continue; }+ let biggest = caps.iter().filter_map(|c| c.1).fold(0.0, f64::max);+ let message = if caps.is_empty() { format!("Rail {net} feeds {loads} IC pin(s) but has no capacitance to ground") } else { format!("Rail {net} feeds {loads} IC pin(s) but has no bulk capacitor (largest is {})", fmt_farads(biggest)) };+ add("info", "bulk_capacitance", caps.iter().map(|c| c.0.clone()).collect(), vec![net.clone()], message,+ format!("Add a 10 uF (or larger) capacitor from {net} to ground where the rail enters the board or leaves its regulator."), json!({}));+ }++ // annotation: a designator not yet annotated, or one designator on two different symbols (one footprint on the board)+ let mut unannotated = BTreeSet::new();+ let mut units: BTreeMap<(String, String), usize> = BTreeMap::new();+ let mut pinsets: BTreeMap<String, Vec<BTreeSet<String>>> = BTreeMap::new();+ for c in parts {+ let des = s(c, &["designator"]);+ if des.is_empty() || des.contains('?') { unannotated.insert(if des.is_empty() { "A symbol".to_string() } else { des }); continue; }+ let unit = s(c, &["unit", "partId", "subpart"]);+ if !unit.is_empty() { *units.entry((des.clone(), unit)).or_default() += 1; }+ else { pinsets.entry(des).or_default().push(c["pins"].as_array().map(|a| a.iter().filter_map(|p| p["number"].as_str().map(String::from)).collect()).unwrap_or_default()); }+ }+ for d in unannotated {+ add("error", "annotation", vec![d.clone()], vec![], format!("{d} is not annotated"), "Annotate the schematic, or give the part a designator, before updating the board: an unannotated part never becomes a footprint.".into(), json!({}));+ }+ let mut dups: BTreeMap<String, usize> = units.into_iter().filter(|(_, n)| *n > 1).map(|((d, _), n)| (d, n)).collect();+ // with no unit field, two symbols sharing a designator and a pin number are two parts, not two units of one+ for (d, sets) in pinsets { if sets.len() > 1 && (0..sets.len()).any(|i| (i + 1..sets.len()).any(|j| !sets[i].is_disjoint(&sets[j]))) { dups.insert(d, sets.len()); } }+ for (d, n) in dups {+ add("error", "annotation", vec![d.clone()], vec![], format!("Reference {d} is used by {n} different symbols"), format!("Renumber one of them or re-annotate: two parts with one designator become one footprint and their nets merge."), json!({}));+ }++ // no_connect_connected: a pin flagged no-connect that is wired to something+ for (key, (des, num, name, ty)) in pins {+ if ty != "not_connected" { continue; }+ let Some(net) = net_of.get(key) else { continue };+ if members(net).len() > 1 {+ add("warning", "no_connect_connected", vec![des.clone()], vec![net.clone()], format!("No-connect flag on {des}.{num} {name} but the pin is wired to {net}"),+ "Either remove the no-connect flag or the wire: the pin is marked unused but carries a net.".into(), json!({"pin": format!("{des}.{num}")}));+ }+ }+ out } /// Symbol pins against footprint pads, part by part: pins with no pad (a net that can never reach copper), pads with no@@ -146,14 +377,27 @@ fn sheet_parts(input: &Value) -> Option<Vec<Value>> { p.get("components").or(Some(&p)).and_then(|x| x.as_array()).cloned() } -/// schematic_review: input {sheetParts, netlist}. The netlist companion is {nets: {net: ["U1.8", ...]}} (or the map).+/// schematic_review: input {sheetParts, netlist}. The netlist companion is {nets: {net: ["U1.8", ...]}, names?: {net:+/// [every label or port name joined into it]}} (or the nets map). Parts may carry value (or comment), libRef (or libId)+/// and unit, which the design checks use. pub fn schematic_review(input: &Value) -> Value { let Some(parts) = sheet_parts(input) else { return crate::input::refuse("bad_args", "pass the sheets' parts (read_sheet_file with pins, every sheet) as sheetParts") }; let Some(n) = crate::input::part(input, "netlist") else { return crate::input::refuse("bad_args", "pass the compiled netlist ({nets: {net: [\"U1.8\", ...]}}) as netlist") }; let nets = n.get("nets").or(Some(&n)).and_then(|x| x.as_object()).cloned().unwrap_or_default(); let mut out = review(&parts, &nets);+ // shorted_nets: two different names joined into one net (two labels on one wire)+ if let Some(names) = n.get("names").and_then(|x| x.as_object()) {+ for (net, ns) in names {+ let mut set: Vec<String> = ns.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default();+ set.sort(); set.dedup();+ if set.len() > 1 {+ out["warnings"].as_array_mut().unwrap().push(json!({"check": "shorted_nets", "refs": [], "nets": [net], "names": set,+ "message": format!("{} name the same net", set.join(" and ")), "fix": "If they are meant to be one net, keep one name; if not, a wire or label joins two nets by mistake: find it and split them."}));+ }+ }+ } out["success"] = json!(true);- out["_hint"] = json!("errors stop a board (a power pin on no net, two outputs on one net); warnings deserve a look (pins on no net, one-pin nets, inputs nothing drives, an IC supply with no capacitor to ground). Pin types come from the symbols: a passive pin is never 'undriven'. Fix on the sheets (sch_connect, sch_place_part), then update_pcb.");+ out["_hint"] = json!("errors stop a board (a power pin on no net, two outputs on one net, a floating reset or enable, a designator unannotated or used twice); warnings deserve a look (pins on no net, one-pin nets, inputs nothing drives, an IC supply with no capacitor to ground, I2C with no pull-up, an LED with no resistor, a regulator without its capacitors, a no-connect flag on a wired pin, two names on one net); infos are gaps (a rail with no bulk capacitor). Each design finding has message and fix. Pin types come from the symbols: a passive pin is never 'undriven'. Fix on the sheets (sch_connect, sch_place_part), then update_pcb."); out } @@ -176,6 +420,51 @@ mod tests { json!({"designator": des, "pins": pins.iter().map(|(n, nm, e)| json!({"number": n, "name": nm, "electrical": e})).collect::<Vec<_>>()}) } + #[test]+ fn the_design_checks_find_kicads_examples() {+ let p = |des: &str, lib: &str, value: &str, pins: &[(&str, &str, &str)]| json!({"designator": des, "libRef": lib, "value": value,+ "pins": pins.iter().map(|(n, nm, e)| json!({"number": n, "name": nm, "electrical": e})).collect::<Vec<_>>()});+ let parts = vec![+ // an MCU on +3V3 with I2C, a reset with only a capacitor on it, and its decoupling+ p("U1", "MCU:X", "", &[("1", "VDD", "power_in"), ("2", "GND", "power_in"), ("3", "SDA", "bidirectional"), ("4", "SCL", "bidirectional"), ("5", "~{RESET}", "input"), ("6", "PA0", "output")]),+ p("C1", "Device:C", "100n", &[("1", "", "passive"), ("2", "", "passive")]),+ p("C2", "Device:C", "100n", &[("1", "", "passive"), ("2", "", "passive")]),+ // an LDO from +12V to +3V3 with no input capacitor and only C1's 100 nF on its output+ p("U2", "Regulator_Linear:AMS1117-3.3", "AMS1117-3.3", &[("1", "GND", "power_in"), ("2", "VO", "power_out"), ("3", "VI", "power_in")]),+ // R1 pulls SCL up; SDA has none+ p("R1", "Device:R", "4k7", &[("1", "", "passive"), ("2", "", "passive")]),+ // an LED straight from a GPIO to ground+ p("D1", "Device:LED", "red", &[("1", "K", "passive"), ("2", "A", "passive")]),+ // two different parts both called C5, and one not annotated+ p("C5", "Device:C", "1u", &[("1", "", "passive"), ("2", "", "passive")]),+ p("C5", "Device:C", "1u", &[("1", "", "passive"), ("2", "", "passive")]),+ p("R?", "Device:R", "10k", &[("1", "", "passive"), ("2", "", "passive")]),+ // a no-connect pin that is wired+ p("U3", "X:Y", "", &[("1", "NC1", "no_connect"), ("2", "IN", "input")]),+ ];+ let nets = json!({"+3V3": ["U1.1", "C1.1", "U2.2", "R1.1", "C5.1"], "/LED": ["U1.6", "D1.2"], "GND": ["U1.2", "C1.2", "U2.1", "C2.2", "D1.1", "C5.2"], "+12V": ["U2.3"],+ "/SDA": ["U1.3", "U3.1"], "/SCL": ["U1.4", "R1.2"], "/NRST": ["U1.5", "C2.1"], "X": ["U3.2"]});+ let r = review(&parts, nets.as_object().unwrap());+ let msgs: Vec<String> = ["errors", "warnings", "infos"].iter().flat_map(|k| r[*k].as_array().unwrap().iter().filter_map(move |f| f["message"].as_str().map(|m| format!("{k}: {m}")))).collect();+ for want in ["warnings: I2C line /SDA has no pull-up resistor to a supply rail",+ "warnings: Nothing sets the level of U1.5 ~{RESET} (net /NRST)",+ "warnings: LED D1 has no series resistor on either side",+ "warnings: Regulator U2 has no input capacitor on +12V",+ "errors: R? is not annotated",+ "errors: Reference C5 is used by 2 different symbols",+ "warnings: No-connect flag on U3.1 NC1 but the pin is wired to /SDA"] {+ assert!(msgs.iter().any(|m| m == want), "missing {want:?} in {msgs:#?}");+ }+ // SCL has its pull-up; the output's biggest capacitor is C5's 1 uF, so no 'only 100n'; +3V3 has no 4.7 uF bulk+ assert!(!msgs.iter().any(|m| m.contains("/SCL")));+ assert!(!msgs.iter().any(|m| m.contains("output +3V3 has only")));+ assert!(msgs.iter().any(|m| m.starts_with("infos: Rail +3V3 feeds")), "{msgs:#?}");+ assert_eq!(farads("4.7uF"), Some(4.7e-6));+ assert_eq!(farads("1u0"), Some(1e-6));+ assert_eq!(farads("100"), None);+ assert!(looks_like_rail("+3V3") && looks_like_rail("3V3") && looks_like_rail("VCC_IO") && !looks_like_rail("SDA"));+ }+ #[test] fn pin_types_come_as_codes_or_names() { assert_eq!(pin_type(&json!(7)), "power");@@ -192,7 +481,7 @@ mod tests { #[test] fn the_review_finds_each_kind_of_problem() { let parts = vec![- part("U1", &[("1", "VCC", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "NC", 0), ("5", "EN", 0)]),+ part("U1", &[("1", "VCC", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "NC", 0), ("5", "EN", 0), ("6", "DATA", 0)]), part("U2", &[("1", "VDD", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "IN", 0)]), part("C1", &[("1", "", 4), ("2", "", 4)]), part("R1", &[("1", "", 4), ("2", "", 4)]),@@ -201,9 +490,12 @@ mod tests { let nets = json!({"3V3": ["U1.1", "C1.1"], "VDD": ["U2.1"], "LX": ["U3.1", "L1.1"], "GND": ["U1.2", "U2.2", "C1.2"], "BUS": ["U1.3", "U2.3"], "SENSE": ["U2.4"], "R": ["R1.1", "R1.2"]}); let r = review(&parts, nets.as_object().unwrap()); let checks = |k: &str| r[k].as_array().unwrap().iter().map(|f| f["check"].as_str().unwrap().to_string()).collect::<Vec<_>>();- // U1.5 EN floats (input, warning); NC is skipped; two outputs share BUS (error)+ // U1.6 DATA floats (input, warning); U1.5 EN floats (a floating enable, error, not also an unconnected pin);+ // NC is skipped; two outputs share BUS (error) assert!(checks("errors").contains(&"outputs_together".to_string())); assert!(checks("warnings").contains(&"unconnected_pin".to_string()));+ assert!(r["errors"].as_array().unwrap().iter().any(|f| f["check"] == "reset_enable" && f["pin"] == "U1.5"), "{r}");+ assert!(!r["warnings"].as_array().unwrap().iter().any(|f| f["pin"] == "U1.5")); assert!(!r["warnings"].as_array().unwrap().iter().any(|f| f["pin"] == "U1.4")); // VDD has one pin and no capacitor; SENSE is an input nothing drives assert!(checks("warnings").contains(&"single_pin_net".to_string()));
dev-skills/altium-bridge-test/run_verb_tests.py+9@@ -113,6 +113,9 @@ def matrix(w): # 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 []))+ # 0.2.86: the standard's log_tail: Altium's Messages panel and log files, offsets that carry from call to call+ M["log_tail"] = dict(phase=1, **ok(sinceOffset=0), check=lambda d: isinstance(d.get("next"), int)+ and w["call"]("altium_log_tail", {"sinceOffset": d["next"]}).get("next", -1) >= d["next"]) M["ensure_licensed"] = dict(phase=1, timeout=300, **ok(), note="defaults only: never signs out, never starts a trial") M["state"] = dict(phase=1, **ok(screenshots=False)) M["eval"] = dict(phase=1, **ok(text="Begin End;"))@@ -415,6 +418,12 @@ def matrix(w): M["sch_delete_wire"] = dict(phase=3.5, **anyo("no wire at that point: refused by name", sheet=LS, at=[1, 1], dryRun=True)) M["sch_edit_label"] = dict(phase=3.5, **anyo("N1's labels planned, or none named", sheet=LS, edits=[{"net": "N1", "by": [0, 0]}], dryRun=True)) M["sch_text"] = dict(phase=3.5, **ok(sheet=LS, texts=[{"text": "battery", "at": [20, 20]}]), check=lambda d: len(d.get("added") or []) == 1)+ # 0.2.86: the standard's sch_batch: two texts in one batch, then a batch whose second op fails must come back restored+ bad_batch = {"filePath": LS, "erc": False, "ops": [{"op": "sch_text", "texts": [{"text": "batch-undone", "at": [24, 40]}]},+ {"op": "sch_connect_pins", "pairs": [{"from": "ZZ9.1", "to": "ZZ8.1"}]}]}+ M["sch_batch"] = dict(phase=3.5, timeout=600, **ok(filePath=LS, erc=False, ops=[{"op": "sch_text", "texts": [{"text": "batch-1", "at": [24, 20]}]},+ {"op": "sch_text", "texts": [{"text": "batch-2", "at": [24, 30]}]}]),+ check=lambda d: len(d.get("results") or []) == 2 and w["call"]("altium_sch_batch", bad_batch).get("restored") is True) M["sch_move_region"] = dict(phase=3.5, **anyo("a planned move, or nothing in the box", sheet=LS, box=[0, 0, 10, 10], by=[0, 2.54], dryRun=True)) M["sch_fix_connectivity"] = dict(phase=3.5, **ok(sheet=LS), check=lambda d: d.get("dryRun") is True and isinstance(d.get("moves"), list)) M["sch_page"] = dict(phase=3.5, **ok(sheet=LS), check=lambda d: (d.get("widthMm") or 0) > 0 and isinstance(d.get("titleBlock"), dict))
package.json+6−2@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.85",+ "version": "0.2.86", "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": [@@ -271,7 +271,11 @@ "altium centroid file", "how long do altium verbs take", "prewarm the altium bridge",- "render my altium board"+ "render my altium board",+ "apply several schematic edits at once in altium",+ "undo a batch of altium schematic changes",+ "altium messages panel warnings",+ "what did altium complain about" ], "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+6−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.85",+ "version": "0.2.86", "hero": { "type": "image", "path": "screenshots/hero.png"@@ -263,7 +263,11 @@ "altium centroid file", "how long do altium verbs take", "prewarm the altium bridge",- "render my altium board"+ "render my altium board",+ "apply several schematic edits at once in altium",+ "undo a batch of altium schematic changes",+ "altium messages panel warnings",+ "what did altium complain about" ], "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.85+0.2.86
src/agent/AdomAgent.pas.tmpl+29@@ -817,6 +817,34 @@ Begin Result := '{' + JRaw('ok', 'true') + ',' + JStr('objectKind', Kind) + ',' + JRaw('messageCount', IntToStr(N)) + ',' + JRaw('messages', '[' + Msgs + ']') + '}'; End; +{ messages: the Messages panel as it stands, compiling nothing (log_tail reads it). limit= caps the count. }+Function CmdMessages(Lines : TStringList) : String;+Var+ WS : IWorkspace;+ MM : IDMMessagesManager;+ I, N, Limit : Integer;+ Msgs : String;+Begin+ Limit := StrToIntDef(Param(Lines, 'limit'), 2000);+ Msgs := ''; N := 0;+ WS := GetWorkspace;+ If WS <> Nil Then+ Begin+ MM := WS.DM_MessagesManager;+ If MM <> Nil Then+ Begin+ N := MM.MessagesCount;+ For I := 0 To N - 1 Do+ Begin+ If I >= Limit Then Break;+ If Msgs <> '' Then Msgs := Msgs + ',';+ Msgs := Msgs + '{' + JStr('class', MM.Messages(I).MsgClass) + ',' + JStr('source', MM.Messages(I).Source) + ',' + JStr('document', MM.Messages(I).Document) + ',' + JStr('text', MM.Messages(I).Text) + '}';+ End;+ End;+ End;+ Result := '{' + JRaw('ok', 'true') + ',' + JRaw('messageCount', IntToStr(N)) + ',' + JRaw('messages', '[' + Msgs + ']') + '}';+End;+ { DRC violations currently on the focused board (run PCB:DesignRuleCheck first). } Function CmdViolations(Lines : TStringList) : String; Var@@ -10212,6 +10240,7 @@ Begin Else If Cmd = 'sim_collect' Then Result := CmdSimCollect(Lines) 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 = 'eval' Then Result := CmdEval(Lines, Payload) Else If Cmd = 'io_bench' Then Result := CmdIoBench(Lines) Else If Cmd = 'read_board' Then Result := CmdReadBoard(Lines)
src/bridge.json+4−2@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.85",+ "version": "0.2.86", "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",@@ -202,6 +202,8 @@ "altium_verb_times", "altium_prewarm", "altium_render_board",+ "altium_log_tail",+ "altium_sch_batch", "altium_route_pair", "altium_routing_drc", "altium_routing_state",@@ -295,7 +297,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,+ "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, "height_check": 150, "copper_balance": 240, "return_path": 240,