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.
main
Colby Knox
0.2.103: update_pcb keeps board-only nets and pairs and returns Altium's Yes/No questions (#39); demo/show surfaces wai…
c97bab4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
//! Hierarchical schematics: a sheet symbol on a parent sheet for a child sheet, its entries joined to the parent's
//! nets, and matching ports on the child. The child is made from Altium's own sheet template and listed in the
//! project when it does not exist yet.
use crate::sch::{agent_data, clean, maybe_save, st};
use crate::{agent, support};
use serde_json::{json, Value};
use std::path::Path;
use std::time::Duration;
/// The project file's text with one more [DocumentN] for `rel` (after the last document section, numbered on).
/// None when it already lists it. Pure, for the tests.
pub fn add_document(prj_text: &str, rel: &str) -> Option<String> {
let norm = |s: &str| s.replace('/', "\\").to_lowercase();
if prj_text.lines().any(|l| l.trim().strip_prefix("DocumentPath=").map(|d| norm(d) == norm(rel)).unwrap_or(false)) { return None; }
let nums: Vec<u32> = prj_text.lines().filter_map(|l| l.trim().strip_prefix("[Document").and_then(|r| r.strip_suffix(']')).and_then(|n| n.parse().ok())).collect();
let n = nums.iter().max().copied().unwrap_or(0) + 1;
let section = format!("[Document{n}]\r\nDocumentPath={rel}\r\nAnnotationEnabled=1\r\n\r\n");
// insert before the first section that follows the last [DocumentN] block, or at the end
let lines: Vec<&str> = prj_text.split_inclusive('\n').collect();
let last_doc = lines.iter().rposition(|l| l.trim().starts_with("[Document") && l.trim().ends_with(']'));
let insert_at = match last_doc {
Some(i) => lines.iter().enumerate().skip(i + 1).find(|(_, l)| l.trim().starts_with('[')).map(|(k, _)| k).unwrap_or(lines.len()),
None => lines.len(),
};
let mut out: String = lines[..insert_at].concat();
if !out.ends_with("\r\n\r\n") && !out.ends_with("\n\n") { if !out.ends_with('\n') { out.push_str("\r\n"); } out.push_str("\r\n"); }
out.push_str(§ion);
out.push_str(&lines[insert_at..].concat());
Some(out)
}
/// The side an entry sits on: as asked, else inputs left and everything else right.
fn side_of(e: &Value) -> &'static str {
match e.get("side").and_then(|s| s.as_str()) {
Some(s) if s.eq_ignore_ascii_case("left") => "left",
Some(s) if s.eq_ignore_ascii_case("right") => "right",
_ => if e.get("io").and_then(|s| s.as_str()).map(|s| s.eq_ignore_ascii_case("input")).unwrap_or(false) { "left" } else { "right" },
}
}
/// altium_sch_sheet_symbol {sheet, child, projectPath?, name?, x?, y?, widthMil?, entries:[{name, io?, side?, net?}], ports?, save?}
pub fn sheet_symbol(args: &Value) -> Value {
if let Some(g) = support::need_licensed() { return g; }
let Some(parent) = support::s(args, "sheet").filter(|p| p.to_lowercase().ends_with(".schdoc")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "sheet (the parent .SchDoc) is required"});
};
let Some(child_arg) = support::s(args, "child").filter(|p| p.to_lowercase().ends_with(".schdoc")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "child (the .SchDoc the symbol stands for) is required"});
};
let pdir = Path::new(&parent).parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default();
let child = if Path::new(&child_arg).is_absolute() || child_arg.contains(':') { child_arg.clone() } else { format!("{pdir}\\{child_arg}") };
let entries = args.get("entries").and_then(|e| e.as_array()).cloned().unwrap_or_default();
if entries.iter().any(|e| st(&e["name"]).is_empty()) {
return json!({"success": false, "errorCode": "bad_args", "error": "every entry needs a name"});
}
let mut steps = Vec::new();
// the child: Altium's own sheet template, when it does not exist yet
let created = !Path::new(&child).exists();
if created {
let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") {
Ok(p) => p,
Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}),
};
if let Err(e) = support::copy_template(&tpl, &child) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }
steps.push(json!({"childCreated": child}));
}
// the project lists the child (a sheet outside the project is not part of the design)
if let Some(prj) = support::s(args, "projectPath") {
match add_to_project(&prj, &child) {
Ok(true) => steps.push(json!({"addedToProject": prj})),
Ok(false) => {}
Err(e) => return e,
}
}
// the symbol on the parent
let left = entries.iter().filter(|e| side_of(e) == "left").count();
let right = entries.len() - left;
let h = ((left.max(right) as i64 + 1) * 100).max(400);
let w = args.get("widthMil").and_then(|v| v.as_i64()).unwrap_or(1400);
let x = args.get("x").and_then(|v| v.as_i64()).unwrap_or(2000) / 100 * 100;
let y = args.get("y").and_then(|v| v.as_i64()).unwrap_or(8000) / 100 * 100;
let stem = Path::new(&child).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
let name = support::s(args, "name").unwrap_or(stem);
let file = crate::routing::rel_to(&pdir, &child);
let payload: Vec<String> = entries.iter().map(|e| format!("{}|{}|{}|{}|{}", clean(&st(&e["name"])), side_of(e), clean(&st(&e["io"])).to_lowercase(),
clean(&st(&e["net"])), e.get("stubMil").and_then(|v| v.as_i64()).unwrap_or(300))).collect();
if let Some(e) = support::must_open(&parent, 60) { return e; }
let r = agent::call("sheet_symbol", &[("x", x.to_string()), ("y", y.to_string()), ("w", w.to_string()), ("h", h.to_string()), ("name", clean(&name)), ("file", clean(&file))],
Some(&payload.join("\n")), Duration::from_secs(90));
let sym = match agent_data(&r) { Ok(d) => d, Err(e) => return e };
let saved_parent = maybe_save(args, &parent);
// the ports on the child, for the entries it lacks
let mut ports = Value::Null;
if args.get("ports").and_then(|b| b.as_bool()) != Some(false) && !entries.is_empty() {
if let Some(e) = support::must_open(&child, 60) { return e; }
let pp: Vec<String> = entries.iter().map(|e| format!("{}|{}", clean(&st(&e["name"])), clean(&st(&e["io"])).to_lowercase())).collect();
let at = args.get("portsAt").cloned().unwrap_or(json!({}));
let n = |k: &str, d: i64| at.get(k).and_then(|v| v.as_i64()).unwrap_or(d).to_string();
let pr = agent::call("sheet_ports", &[("left", n("left", 1000)), ("right", n("right", 15000)), ("top", n("top", 9500))], Some(&pp.join("\n")), Duration::from_secs(90));
ports = match agent_data(&pr) { Ok(d) => json!({"placed": d["placed"], "alreadyThere": d["alreadyThere"]}), Err(e) => return e };
let _ = maybe_save(args, &child);
}
json!({"success": true, "parent": parent, "child": child, "childCreated": created, "symbol": {"name": sym["name"], "file": sym["file"], "atMil": [x, y], "sizeMil": [w, h], "entries": sym["entries"]},
"ports": ports, "savedParent": saved_parent, "steps": steps,
"_hint": "Wire the child's circuit to its ports: altium_sch_connect {sheet: child, connections:[{designator, pin, net: <port name>, kind:'port'}]} or a wire from a pin to the port's stubEndMil. Then altium_compile {projectPath}: the entries and ports join by name, and the parent's nets reach the child."})
}
/// Compare a compiled netlist with the nets the caller expects: each expected net's missing and extra pins, and nets
/// joined that were not expected (two or more pins). Pure, for the tests.
pub fn compare(got: &serde_json::Map<String, Value>, want: &serde_json::Map<String, Value>) -> Vec<Value> {
use std::collections::BTreeSet;
let set = |v: &Value| -> BTreeSet<String> { v.as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(|s| s.to_uppercase())).collect() };
let find = |n: &str| got.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| set(v)).unwrap_or_default();
let mut out = Vec::new();
for (net, pins) in want {
let (w, g) = (set(pins), find(net));
if w != g { out.push(json!({"net": net, "missing": w.difference(&g).collect::<Vec<_>>(), "extra": g.difference(&w).collect::<Vec<_>>()})); }
}
for (net, pins) in got {
if !want.keys().any(|k| k.eq_ignore_ascii_case(net)) && set(pins).len() > 1 { out.push(json!({"net": net, "unexpected": pins})); }
}
out
}
/// altium_netlist {projectPath, net?, expect?}: compile the project and read its nets (every sheet, hierarchy
/// resolved) as {net: ["U1.3", ...]}; with expect, compare pin by pin.
pub fn netlist(args: &Value) -> Value {
if let Some(g) = support::need_licensed() { return g; }
let Some(prj) = support::s(args, "projectPath").filter(|p| p.to_lowercase().ends_with(".prjpcb")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"});
};
// the project focused: its own file opened, then its first sheet (the netlist reads the FOCUSED project)
agent::call("open", &[("path", prj.clone())], None, Duration::from_secs(120));
let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
let dir = Path::new(&prj).parent().unwrap_or(Path::new("."));
if let Some(first) = crate::bom::parse_project(&text, dir).sheets.first() {
if let Some(e) = support::must_open(first, 60) { return e; }
}
let c = agent::call("compile", &[("objectKind", "Project".into())], None, Duration::from_secs(300));
let n = agent::call("project_nets", &[], None, Duration::from_secs(120));
let d = match agent_data(&n) { Ok(d) => d, Err(e) => return e };
if !d["project"].as_str().map(|p| p.eq_ignore_ascii_case(&prj.replace('/', "\\"))).unwrap_or(false)
&& !d["project"].as_str().map(|p| Path::new(p).file_name() == Path::new(&prj).file_name()).unwrap_or(false) {
return json!({"success": false, "errorCode": "wrong_project", "error": format!("Altium compiled {} instead", d["project"]), "_hint": "Open a sheet of the project you mean (altium_open_document), then call again."});
}
let mut nets = d["nets"].as_object().cloned().unwrap_or_default();
if let Some(want) = support::s(args, "net") { nets.retain(|k, _| k.eq_ignore_ascii_case(&want)); }
let errors: Vec<Value> = c.get("data").and_then(|x| x.get("messages")).and_then(|m| m.as_array()).cloned().unwrap_or_default()
.into_iter().filter(|m| m["class"].as_str().map(|k| k.to_lowercase().contains("error")).unwrap_or(false)).collect();
let mut out = json!({"success": true, "project": prj, "netCount": d["netCount"], "nets": nets, "compileErrors": errors,
"_hint": "Pins are Designator.PinNumber across every sheet, the hierarchy resolved (a net named by a port or entry carries its parent's name). Pass expect:{net:[pins]} to compare."});
if let Some(want) = args.get("expect").and_then(|e| e.as_object()) {
let mm = compare(&d["nets"].as_object().cloned().unwrap_or_default(), want);
out["success"] = json!(mm.is_empty());
out["mismatches"] = json!(mm);
}
out
}
/// List `doc` in the project file `prj` (relative to it). Rewriting an open project's file makes Altium ask to reload
/// it, so its open members are saved and closed first and the project reopened after. Ok(false) when it was listed.
pub(crate) fn add_to_project(prj: &str, doc: &str) -> Result<bool, Value> {
let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
if text.is_empty() { return Err(json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj} could not be read")})); }
let prj_dir = Path::new(prj).parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default();
let Some(new_text) = add_document(&text, &crate::routing::rel_to(&prj_dir, doc)) else { return Ok(false) };
let (open, unlisted) = crate::routing::project_members(Path::new(prj));
if !unlisted.is_empty() {
return Err(json!({"success": false, "errorCode": "project_has_unlisted_documents", "error": format!("{prj} is open with documents its file does not list: {}", unlisted.join(", ")),
"_hint": "Save or close those documents first (altium_save / altium_close_document), then call again."}));
}
crate::routing::close_project_saved(prj, &open);
if let Err(e) = std::fs::write(prj, new_text) { return Err(json!({"success": false, "errorCode": "write_failed", "error": format!("{prj}: {e}")})); }
agent::call("open", &[("path", prj.to_string())], None, Duration::from_secs(120));
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_child_sheet_joins_the_project_after_its_last_document() {
let prj = "[Design]\r\nVersion=1.0\r\n\r\n[Document1]\r\nDocumentPath=lane.SchDoc\r\n\r\n[Document2]\r\nDocumentPath=lane.PcbDoc\r\n\r\n[ProjectVariant1]\r\nDescription=Lite\r\n";
let out = add_document(prj, "Power.SchDoc").unwrap();
assert!(out.contains("[Document3]\r\nDocumentPath=Power.SchDoc\r\n"));
assert!(out.find("[Document3]").unwrap() < out.find("[ProjectVariant1]").unwrap());
assert!(add_document(&out, "power.schdoc").is_none());
assert!(add_document("[Design]\r\nVersion=1.0\r\n", "A.SchDoc").unwrap().contains("[Document1]\r\nDocumentPath=A.SchDoc"));
}
#[test]
fn netlist_comparison_names_missing_extra_and_unexpected() {
let got = json!({"VBUS": ["U1.1", "U10.1"], "NetU2_3": ["U2.3", "U10.3"], "GND": ["U1.4"]});
let want = json!({"vbus": ["u1.1", "U10.1"], "GND": ["U1.4", "U2.4"]});
let mm = compare(got.as_object().unwrap(), want.as_object().unwrap());
assert_eq!(mm.len(), 2);
assert_eq!(mm[0]["missing"], json!(["U2.4"]));
assert_eq!(mm[1]["net"], json!("NetU2_3"));
}
#[test]
fn inputs_go_left_and_the_rest_right_unless_asked() {
assert_eq!(side_of(&json!({"io": "input"})), "left");
assert_eq!(side_of(&json!({"io": "output"})), "right");
assert_eq!(side_of(&json!({"io": "output", "side": "left"})), "left");
assert_eq!(side_of(&json!({})), "right");
}
}