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.76 source, continued (still unreleased): 14 schematic wiring verbs from the EDA Bridge Standard in mm (sch_items, sch_pins, sch_trace_point, sch_connect_pins, sch_bus, sch_bus_entry, sch_connect_to_bus, sch_junction, sch_split_wire, sch_delete_wire, sch_edit_label, sch_text, sch_move_region, sch_fix_connectivity); agent sch_dump/sch_ops; 216 verbs
12 files changed
+1336−13
CHANGELOG.md+8@@ -5,6 +5,14 @@ - `altium_move_parts`: flips parts. `side: "top" | "bottom"` puts a part on that side and `flip: true` turns it over; the side is read back with position and rotation. The EDA Bridge Standard asked for flipping as an argument on move_parts rather than a verb of its own.+- **Schematic wiring as data** (14 new verbs, the EDA Bridge Standard's batch 1 from kicad-lane): `sch_items`,+ `sch_pins`, `sch_trace_point`, `sch_connect_pins`, `sch_bus`, `sch_bus_entry`, `sch_connect_to_bus`, `sch_junction`,+ `sch_split_wire`, `sch_delete_wire`, `sch_edit_label`, `sch_text`, `sch_move_region`, `sch_fix_connectivity`. In mm+ on the sheet's frame, pins as Ref.Pin; ids are a hash of each item's kind and geometry (Altium items have none).+ The agent gained two general commands (dump a sheet's wiring; apply primitive steps as one undo step) and the+ planning is Rust, unit-tested (connectivity with Altium's rules: T joins, crossings only at a dot, same-name labels).+ Tested on Altium Develop: wire pin pairs, a three-pin bus fan-out with entries and labels, split, delete, label+ edits, a region moved and back with every pin still on its net. - `altium_bodies` (new): every part's 3D bodies as boxes in mm, the standard's bodies model (`{ref, side, x0, y0, x1, y1, z0, z1}`), plus the parts with no body. The data `height_check` already read, now its own verb, so the shared checks engine and other tools can read it.
README.md+18−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 -202 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+216 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. 202 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 216 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 202 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 216 `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 202 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 216 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -325,6 +325,20 @@ All 202 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_sch_swap_part`: Replace a placed part with another library part (a different value, package or symbol) at the same place, designator and rotation, keeping its connections: where a new pin ends elsewhere, a wire joins it to where the old pin ended. - `altium_sch_connect`: Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). - `altium_sch_edit`: Change placed parts on a sheet: move (to x,y mil), moveBy (dx,dy), rotate (degrees), rename (designator), re-comment (comment), delete.+- `altium_sch_items`: List a sheet's wiring items with ids and coordinates: wires, buses, bus entries, net labels (local, global, hierarchical), power ports, junctions, no-connect markers, texts and sheet symbols.+- `altium_sch_pins`: Every pin of the named parts on a sheet: its absolute position (rotation and mirror applied), number, name, electrical type, the side it leaves the body, and the wires, labels and nets touching it.+- `altium_sch_trace_point`: Everything electrically connected at a point on a sheet: the wires, labels, pins, junctions, sheet pins and no-connect markers there, and for each net they belong to the whole net with its name.+- `altium_sch_junction`: Add junction dots at points, or remove dots by id or point.+- `altium_sch_bus`: Draw a bus as a polyline (one bus segment per pair of points), optionally with a bus label such as D[0..7] or a group {SDA SCL} at its first point.+- `altium_sch_bus_entry`: Add 45-degree bus entries: the short diagonal that joins a member wire's end to a bus.+- `altium_sch_split_wire`: Split the wire through a point into two wires there, with a junction dot at the cut, so a new branch can end on a wire end.+- `altium_sch_delete_wire`: Delete wires or bus segments by id, by their two ends, or every wire through a point, and remove junction dots that no longer join three or more items.+- `altium_sch_edit_label`: Edit net labels: rotate, move to a point or by a delta, rename, or move every label of a net at once.+- `altium_sch_text`: Add free text to a sheet (a note, a title, a design comment) with size, angle, justification, bold and italic.+- `altium_sch_connect_pins`: Wire pins to pins on a sheet by Ref.Pin: an L-shaped route (one horizontal and one vertical leg) for each pair, with a junction dot wherever a route meets an existing wire in a T.+- `altium_sch_connect_to_bus`: Fan pins onto a bus: for each pin a wire running to the bus, a 45-degree bus entry onto it and a member label (D0, D1 ...) on the wire.+- `altium_sch_move_region`: Move everything inside a box by (dx, dy): parts, wire ends inside the box (wires crossing its edge stretch), labels, junctions, no-connect markers, texts, bus entries and sheet symbols.+- `altium_sch_fix_connectivity`: Snap near-miss wire ends onto the pin, label, sheet pin or wire end they almost touch, within a tolerance. - `altium_annotate`: Number every '?' designator (R?, C?, U?) across the project's sheets: the lowest free number per prefix, top-left first on each sheet. - `altium_doc_params`: Read or set a sheet's document parameters: the title block (Title, DocumentNumber, Revision, DrawnBy, Author, CompanyName, ...). - `altium_update_pcb`: Design > Update PCB Document from the schematic (the engineering change order): parts added, removed or renamed, nets and footprints updated on the board.
bridge-rs/src/main.rs+1@@ -12,6 +12,7 @@ mod bom; mod sch; mod schdoc; mod schreview;+mod schwire; mod design; mod dialogs; mod health;
bridge-rs/src/routing.rs+1−1@@ -38,7 +38,7 @@ pub fn layer_name(id: i64) -> String { } /// FNV-1a 64: stable across builds (std's hasher is not), plenty for change detection.-fn fnv(s: &str) -> String {+pub(crate) fn fnv(s: &str) -> String { let mut h: u64 = 0xcbf29ce484222325; for b in s.as_bytes() { h ^= *b as u64;
bridge-rs/src/sch.rs+1−1@@ -12,7 +12,7 @@ pub(crate) fn st(v: &Value) -> String { v.as_str().map(str::to_string).unwrap_or pub(crate) fn clean(v: &str) -> String { v.replace(['|', '\n', '\r'], " ") } -fn need_sheet(args: &Value) -> Result<String, Value> {+pub(crate) fn need_sheet(args: &Value) -> Result<String, Value> { let Some(sheet) = s(args, "sheet").or_else(|| s(args, "filePath")) else { return Err(json!({"success": false, "errorCode": "bad_args", "error": "sheet (.SchDoc path) is required"})); };
bridge-rs/src/schwire.rsadded+874@@ -0,0 +1,874 @@+//! Schematic wiring as data: the EDA Bridge Standard's sch_* wiring verbs on Altium (adom/eda-bridge-standard,+//! proposed by kicad-lane, batch 1). The agent only dumps a sheet (`sch_dump`) and applies primitive steps as one undo+//! step (`sch_ops`); reading, planning and checking happen here, over plain data, so they are unit-tested.+//!+//! The standard's schematic frame: millimetres, the sheet's origin, y up (Altium's own frame, in mm instead of mils),+//! pins as Ref.Pin. Altium gives wires, labels and junctions no stable id, so an item's id is a hash of its kind and+//! geometry: valid until the item changes, and every edit answers the new ids.+use crate::sch::{agent_data, clean, maybe_save, need_sheet, st};+use crate::support::{self, timeout_of};+use crate::agent;+use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};++type P = (i64, i64);++#[derive(Debug, Clone, Default)]+pub struct Item {+ pub t: char,+ pub key: String,+ pub pts: Vec<P>,+ pub at: P,+ pub corner: P,+ pub text: String,+ pub rot: i64,+ pub w: i64,+ pub h: i64,+ pub file: String,+ pub entries: Vec<(String, i64, i64, i64)>,+}++#[derive(Debug, Clone, Default)]+pub struct Pin { pub r: String, pub num: String, pub name: String, pub elec: i64, pub at: P, pub dir: i64, pub hidden: bool }++#[derive(Debug, Clone, Default)]+pub struct Comp { pub r: String, pub at: P, pub lib: String }++#[derive(Debug, Clone, Default)]+pub struct Sheet { pub k: f64, pub items: Vec<Item>, pub pins: Vec<Pin>, pub comps: Vec<Comp>, pub page: Value, pub document: String }++fn r4(v: f64) -> f64 { (v * 10000.0).round() / 10000.0 }++impl Sheet {+ /// raw units to mm (k is raw units per inch)+ pub fn mm(&self, v: i64) -> f64 { r4(v as f64 * 25.4 / self.k) }+ pub fn raw(&self, mm: f64) -> i64 { (mm * self.k / 25.4).round() as i64 }+ pub fn pt(&self, p: P) -> Value { json!([self.mm(p.0), self.mm(p.1)]) }+ fn tol(&self) -> i64 { ((self.k / 25.4) * 0.001).round().max(1.0) as i64 }+}++/// An item's id: its kind and a hash of its key (kind, geometry, text).+pub fn id_of(key: &str) -> String {+ let kind = match key.chars().next() {+ Some('W') => "wire", Some('B') => "bus", Some('E') => "entry", Some('J') => "junction", Some('X') => "noconnect",+ Some('N') => "label", Some('P') => "port", Some('O') => "power", Some('T') => "text", Some('S') => "sheet", _ => "item",+ };+ format!("{kind}-{}", &crate::routing::fnv(key)[..10])+}++pub fn parse(d: &Value) -> Sheet {+ let k = d["k"].as_f64().filter(|k| *k > 0.0).unwrap_or(10_000_000.0);+ let i = |v: &Value| v.as_i64().unwrap_or(0);+ let mut sh = Sheet { k, page: d["page"].clone(), document: st(&d["document"]), ..Default::default() };+ for it in d["items"].as_array().cloned().unwrap_or_default() {+ let t = st(&it["t"]).chars().next().unwrap_or('?');+ if t == 'C' {+ sh.comps.push(Comp { r: st(&it["ref"]), at: (i(&it["x"]), i(&it["y"])), lib: st(&it["lib"]) });+ continue;+ }+ let pts: Vec<P> = it["pts"].as_array().cloned().unwrap_or_default().iter().map(|p| (i(&p[0]), i(&p[1]))).collect();+ let entries = it["entries"].as_array().cloned().unwrap_or_default().iter()+ .map(|e| (st(&e[0]), i(&e[1]), i(&e[2]), i(&e[3]))).collect();+ sh.items.push(Item { t, key: st(&it["key"]), pts, at: (i(&it["x"]), i(&it["y"])), corner: (i(&it["cx"]), i(&it["cy"])),+ text: st(&it["text"]), rot: i(&it["rot"]), w: i(&it["w"]), h: i(&it["h"]), file: st(&it["file"]), entries });+ }+ for p in d["pins"].as_array().cloned().unwrap_or_default() {+ sh.pins.push(Pin { r: st(&p[0]), num: st(&p[1]), name: st(&p[2]), elec: i(&p[3]), at: (i(&p[4]), i(&p[5])), dir: i(&p[6]), hidden: p[7].as_bool() == Some(true) });+ }+ sh+}++// -- geometry -----------------------------------------------------------------------------------------------------++/// p on segment a-b (within tol), and whether strictly inside it (not at an end)+fn on_seg(p: P, a: P, b: P, tol: i64) -> (bool, bool) {+ let (dx, dy) = ((b.0 - a.0) as f64, (b.1 - a.1) as f64);+ let l2 = dx * dx + dy * dy;+ let near = |q: P| (q.0 - p.0).abs() <= tol && (q.1 - p.1).abs() <= tol;+ if near(a) || near(b) { return (true, false); }+ if l2 == 0.0 { return (false, false); }+ let t = (((p.0 - a.0) as f64) * dx + ((p.1 - a.1) as f64) * dy) / l2;+ if !(0.0..=1.0).contains(&t) { return (false, false); }+ let (qx, qy) = (a.0 as f64 + t * dx, a.1 as f64 + t * dy);+ let on = (qx - p.0 as f64).abs() <= tol as f64 && (qy - p.1 as f64).abs() <= tol as f64;+ (on, on)+}++fn same(a: P, b: P, tol: i64) -> bool { (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol }++/// A sheet entry's point on its symbol's edge (Altium: Side 0 left, 1 right, 2 top, 3 bottom; distance from the top+/// or the left).+pub fn entry_point(s: &Item, side: i64, dist: i64) -> P {+ match side { 1 => (s.at.0 + s.w, s.at.1 - dist), 2 => (s.at.0 + dist, s.at.1), 3 => (s.at.0 + dist, s.at.1 - s.h), _ => (s.at.0, s.at.1 - dist) }+}++/// A port's two connection ends (it is drawn from Location along its width).+fn port_ends(p: &Item) -> [P; 2] { [p.at, (p.at.0 + p.w, p.at.1)] }++fn segs(it: &Item) -> Vec<(P, P)> { it.pts.windows(2).map(|w| (w[0], w[1])).collect() }++// -- connectivity ---------------------------------------------------------------------------------------------------++/// A node of the sheet's connectivity graph.+#[derive(Debug, Clone, PartialEq)]+pub enum Node { Wire(usize), Pin(usize), Item(usize), Entry(usize, usize) }++/// Groups of electrically joined nodes on one sheet, with Altium's rules: a wire end joins another wire anywhere+/// along it (a T) and a wire end; crossing middles join only at a junction; labels, power ports, ports and junctions+/// join a wire anywhere along it; pins and sheet entries join wire ends (and each other when they touch); labels and+/// power ports with the same text are the same net.+pub struct Graph { pub nodes: Vec<Node>, pub group: Vec<usize> }++fn find(p: &mut Vec<usize>, x: usize) -> usize { let mut r = x; while p[r] != r { r = p[r]; } let mut y = x; while p[y] != r { let n = p[y]; p[y] = r; y = n; } r }++pub fn graph(sh: &Sheet) -> Graph {+ let tol = sh.tol();+ let mut nodes = Vec::new();+ for (i, it) in sh.items.iter().enumerate() { if it.t == 'W' { nodes.push(Node::Wire(i)); } }+ for i in 0..sh.pins.len() { nodes.push(Node::Pin(i)); }+ for (i, it) in sh.items.iter().enumerate() {+ match it.t { 'N' | 'O' | 'P' | 'J' | 'X' => nodes.push(Node::Item(i)), 'S' => for e in 0..it.entries.len() { nodes.push(Node::Entry(i, e)) }, _ => {} }+ }+ let n = nodes.len();+ let mut par: Vec<usize> = (0..n).collect();+ // the points each node offers, and whether it joins a wire's middle+ let pts_of = |nd: &Node| -> (Vec<P>, bool) {+ match nd {+ Node::Pin(i) => (vec![sh.pins[*i].at], false),+ Node::Item(i) => { let it = &sh.items[*i]; if it.t == 'P' { (port_ends(it).to_vec(), true) } else { (vec![it.at], it.t != 'X') } }+ Node::Entry(i, e) => { let it = &sh.items[*i]; let (_, side, dist, _) = &it.entries[*e]; (vec![entry_point(it, *side, *dist)], false) }+ Node::Wire(_) => (vec![], false),+ }+ };+ let ends = |i: usize| -> Vec<P> { let p = &sh.items[i].pts; if p.is_empty() { vec![] } else { vec![p[0], p[p.len() - 1]] } };+ for a in 0..n {+ for b in (a + 1)..n {+ let join = match (&nodes[a], &nodes[b]) {+ (Node::Wire(i), Node::Wire(j)) => {+ let (si, sj) = (segs(&sh.items[*i]), segs(&sh.items[*j]));+ ends(*i).iter().any(|p| sj.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0)) || ends(*j).iter().any(|p| si.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0))+ // crossing middles joined by a junction dot+ || sh.items.iter().filter(|it| it.t == 'J').any(|jn| si.iter().any(|(x, y)| on_seg(jn.at, *x, *y, tol).0) && sj.iter().any(|(x, y)| on_seg(jn.at, *x, *y, tol).0))+ }+ (Node::Wire(w), o) | (o, Node::Wire(w)) => {+ let (ps, middle) = pts_of(o);+ let s = segs(&sh.items[*w]);+ ps.iter().any(|p| if middle { s.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0) } else { ends(*w).iter().any(|e| same(*e, *p, tol)) || s.iter().any(|(x, y)| on_seg(*p, *x, *y, tol).0 && !on_seg(*p, *x, *y, tol).1 ) })+ }+ (x, y) => {+ let (px, _) = pts_of(x);+ let (py, _) = pts_of(y);+ let touch = px.iter().any(|p| py.iter().any(|q| same(*p, *q, tol)));+ let named = |nd: &Node| match nd { Node::Item(i) if matches!(sh.items[*i].t, 'N' | 'O') => Some(sh.items[*i].text.to_uppercase()), _ => None };+ touch || matches!((named(x), named(y)), (Some(a), Some(b)) if a == b)+ }+ };+ if join { let (ra, rb) = (find(&mut par, a), find(&mut par, b)); if ra != rb { par[ra] = rb; } }+ }+ }+ let group = (0..n).map(|i| find(&mut par, i)).collect();+ Graph { nodes, group }+}++/// The nets of a sheet: per group, its name (power port, then net label, then port, then sheet entry) and members.+pub fn nets(sh: &Sheet, g: &Graph) -> Vec<Value> {+ let mut by: BTreeMap<usize, Vec<usize>> = BTreeMap::new();+ for (i, gr) in g.group.iter().enumerate() { by.entry(*gr).or_default().push(i); }+ let mut out = Vec::new();+ for (_, members) in by {+ let (mut pins, mut labels, mut power, mut ports, mut wires, mut entries) = (vec![], vec![], vec![], vec![], vec![], vec![]);+ for m in &members {+ match &g.nodes[*m] {+ Node::Pin(i) => pins.push(format!("{}.{}", sh.pins[*i].r, sh.pins[*i].num)),+ Node::Wire(i) => wires.push(id_of(&sh.items[*i].key)),+ Node::Item(i) => { let it = &sh.items[*i]; match it.t { 'N' => labels.push(it.text.clone()), 'O' => power.push(it.text.clone()), 'P' => ports.push(it.text.clone()), _ => {} } }+ Node::Entry(i, e) => entries.push(sh.items[*i].entries[*e].0.clone()),+ }+ }+ if pins.is_empty() && labels.is_empty() && power.is_empty() && ports.is_empty() && entries.is_empty() { continue; } // a lone wire or dot+ let mut names: Vec<String> = power.iter().chain(labels.iter()).chain(ports.iter()).chain(entries.iter()).cloned().collect();+ names.dedup();+ let name = names.first().cloned().unwrap_or_else(|| pins.first().map(|p| format!("Net{}", p.replace('.', "_"))).unwrap_or_default());+ labels.sort(); labels.dedup(); power.sort(); power.dedup();+ out.push(json!({"name": name, "pins": pins, "labels": labels, "powerPorts": power, "ports": ports, "sheetEntries": entries, "wires": wires,+ "leavesSheet": !power.is_empty() || !ports.is_empty() || !entries.is_empty()}));+ }+ out+}++// -- the agent round trips ------------------------------------------------------------------------------------------++fn load(args: &Value) -> Result<(String, Sheet), Value> {+ if let Some(g) = support::need_licensed() { return Err(g); }+ let sheet = need_sheet(args)?;+ if let Some(e) = support::must_open(&sheet, 60) { return Err(e); }+ let r = agent::call("sch_dump", &[], None, timeout_of(args, 120));+ let d = agent_data(&r)?;+ Ok((sheet, parse(&d)))+}++fn apply(args: &Value, ops: &[String]) -> Result<Vec<Value>, Value> {+ if ops.is_empty() { return Ok(vec![]); }+ let r = agent::call("sch_ops", &[], Some(&ops.join("\n")), timeout_of(args, 120));+ let d = agent_data(&r)?;+ Ok(d["results"].as_array().cloned().unwrap_or_default())+}++fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }++fn pts_arg(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }++fn raw_pts(_sh: &Sheet, pts: &[P]) -> String { pts.iter().map(|p| format!("{},{}", p.0, p.1)).collect::<Vec<_>>().join(",") }++fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }++fn kind_name(t: char) -> &'static str {+ match t { 'W' => "wire", 'B' => "bus", 'E' => "busEntry", 'J' => "junction", 'X' => "noConnect", 'N' => "label", 'P' => "port", 'O' => "powerPort", 'T' => "text", 'S' => "sheet", _ => "item" }+}++fn by_id<'a>(sh: &'a Sheet, id: &str) -> Option<(usize, &'a Item)> { sh.items.iter().enumerate().find(|(_, it)| id_of(&it.key) == id) }++/// Ids of the items a step created or changed, from the agent's per-step keys.+fn new_ids(results: &[Value]) -> Vec<Value> { results.iter().filter_map(|r| r["key"].as_str().filter(|k| !k.is_empty()).map(|k| json!(id_of(k)))).collect() }++fn failed(results: &[Value]) -> Vec<Value> { results.iter().filter(|r| r["result"] != json!("ok")).cloned().collect() }++// -- verbs ----------------------------------------------------------------------------------------------------------++/// altium_sch_items {sheet, kinds?}+pub fn items(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let want: Option<Vec<String>> = args.get("kinds").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(str::to_string).collect());+ let on = |k: &str| want.as_ref().map(|w| w.iter().any(|x| x == k)).unwrap_or(true);+ let mut out = BTreeMap::new();+ for k in ["wires", "buses", "busEntries", "labels", "powerPorts", "junctions", "noConnects", "texts", "sheets"] { out.insert(k, Vec::<Value>::new()); }+ for it in &sh.items {+ let id = id_of(&it.key);+ let (k, v) = match it.t {+ 'W' | 'B' => (if it.t == 'W' { "wires" } else { "buses" }, json!({"id": id, "from": sh.pt(it.pts[0]), "to": sh.pt(*it.pts.last().unwrap_or(&it.pts[0])), "points": it.pts.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>()})),+ 'E' => ("busEntries", json!({"id": id, "at": sh.pt(it.at), "end": sh.pt(it.corner)})),+ 'N' => ("labels", json!({"id": id, "text": it.text, "kind": "local", "at": sh.pt(it.at), "rotation": it.rot * 90})),+ 'P' => ("labels", json!({"id": id, "text": it.text, "kind": "hierarchical", "at": sh.pt(it.at), "rotation": 0, "altium": "port", "widthMm": sh.mm(it.w)})),+ 'O' => ("powerPorts", json!({"id": id, "net": it.text, "at": sh.pt(it.at), "rotation": it.rot * 90})),+ 'J' => ("junctions", json!({"id": id, "at": sh.pt(it.at)})),+ 'X' => ("noConnects", json!({"id": id, "at": sh.pt(it.at)})),+ 'T' => ("texts", json!({"id": id, "text": it.text, "at": sh.pt(it.at), "rotation": it.rot * 90})),+ 'S' => ("sheets", json!({"id": id, "name": it.text, "file": it.file, "at": sh.pt(it.at), "sizeMm": [sh.mm(it.w), sh.mm(it.h)],+ "pins": it.entries.iter().map(|(n, side, dist, _)| json!({"name": n, "at": sh.pt(entry_point(it, *side, *dist))})).collect::<Vec<_>>()})),+ _ => continue,+ };+ if on(k) { out.get_mut(k).unwrap().push(v); }+ }+ let counts: BTreeMap<&str, usize> = out.iter().map(|(k, v)| (*k, v.len())).collect();+ let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "counts": counts,+ "_hint": "Ids are Altium items' kind plus a hash of their geometry: valid until the item changes; every edit verb answers the new ids. Altium's ports are listed as hierarchical labels (altium: port). Parts are in altium_schematic_data; pins in altium_sch_pins."});+ for (k, v) in out { if on(k) { r[k] = json!(v); } }+ r+}++fn dir_name(d: i64) -> &'static str { match d { 0 => "right", 1 => "up", 2 => "left", _ => "down" } }++fn pin_type(e: i64) -> &'static str { crate::schreview::electrical(e) }++/// altium_sch_pins {sheet, references?, connections?}+pub fn pins(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let refs: Option<Vec<String>> = args.get("references").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(|x| x.to_uppercase()).collect());+ let conn = args.get("connections").and_then(|v| v.as_bool()) != Some(false);+ let g = if conn { Some(graph(&sh)) } else { None };+ let nets_all = g.as_ref().map(|g| nets(&sh, g)).unwrap_or_default();+ let tol = sh.tol();+ let mut out = Vec::new();+ for (pi, p) in sh.pins.iter().enumerate() {+ if let Some(rs) = &refs { if !rs.contains(&p.r.to_uppercase()) { continue; } }+ let mut v = json!({"ref": p.r, "number": p.num, "name": p.name, "type": pin_type(p.elec), "at": sh.pt(p.at), "direction": dir_name(p.dir), "hidden": p.hidden});+ if let Some(g) = &g {+ let me = g.nodes.iter().position(|n| *n == Node::Pin(pi)).unwrap();+ let grp = g.group[me];+ let touching: Vec<Value> = sh.items.iter().filter(|it| match it.t {+ 'W' => it.pts.first().map(|a| same(*a, p.at, tol)).unwrap_or(false) || it.pts.last().map(|a| same(*a, p.at, tol)).unwrap_or(false),+ 'N' | 'O' | 'J' | 'X' => same(it.at, p.at, tol),+ 'P' => port_ends(it).iter().any(|e| same(*e, p.at, tol)),+ _ => false }).map(|it| json!({"kind": kind_name(it.t), "id": id_of(&it.key)})).collect();+ let others: Vec<String> = g.nodes.iter().enumerate().filter(|(i, n)| g.group[*i] == grp && *i != me && matches!(n, Node::Pin(_)))+ .map(|(_, n)| if let Node::Pin(j) = n { format!("{}.{}", sh.pins[*j].r, sh.pins[*j].num) } else { String::new() }).collect();+ let key = format!("{}.{}", p.r, p.num);+ let net_names: Vec<Value> = nets_all.iter().filter(|n| n["pins"].as_array().map(|a| a.iter().any(|x| x == &json!(key))).unwrap_or(false)).map(|n| n["name"].clone()).collect();+ v["touching"] = json!(touching); v["nets"] = json!(net_names); v["connectedPins"] = json!(others);+ }+ out.push(v);+ }+ json!({"success": true, "sheet": sheet, "units": "mm", "pins": out,+ "_hint": "at is the pin's outer end: where a wire or label must land. connectedPins are the other pins on the same wiring of this sheet; nets leaving the sheet continue through power ports and ports (altium_netlist has the compiled nets)."})+}++/// altium_sch_trace_point {sheet, at, toleranceMm?}+pub fn trace_point(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let Some(at) = args.get("at").and_then(pts_arg) else { return bad("at: [x, y] mm is required") };+ let p = (sh.raw(at.0), sh.raw(at.1));+ let tol = sh.raw(args.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.05)).max(1);+ let g = graph(&sh);+ let mut items = Vec::new();+ let mut groups = BTreeSet::new();+ let mut interior_wires = 0;+ for (ni, n) in g.nodes.iter().enumerate() {+ let hit = match n {+ Node::Wire(i) => { let s = segs(&sh.items[*i]); let h = s.iter().map(|(a, b)| on_seg(p, *a, *b, tol)).find(|x| x.0); if let Some((_, inside)) = h { if inside { interior_wires += 1; } true } else { false } }+ Node::Pin(i) => same(sh.pins[*i].at, p, tol),+ Node::Item(i) => { let it = &sh.items[*i]; if it.t == 'P' { port_ends(it).iter().any(|e| same(*e, p, tol)) } else { same(it.at, p, tol) } }+ Node::Entry(i, e) => { let it = &sh.items[*i]; let (_, side, dist, _) = &it.entries[*e]; same(entry_point(it, *side, *dist), p, tol) }+ };+ if !hit { continue; }+ groups.insert(g.group[ni]);+ let v = match n {+ Node::Wire(i) => json!({"kind": "wire", "id": id_of(&sh.items[*i].key), "at": sh.pt(p)}),+ Node::Pin(i) => json!({"kind": "pin", "id": format!("{}.{}", sh.pins[*i].r, sh.pins[*i].num), "at": sh.pt(sh.pins[*i].at)}),+ Node::Item(i) => json!({"kind": kind_name(sh.items[*i].t), "id": id_of(&sh.items[*i].key), "at": sh.pt(sh.items[*i].at), "text": sh.items[*i].text}),+ Node::Entry(i, e) => json!({"kind": "sheetPin", "id": format!("{}/{}", id_of(&sh.items[*i].key), sh.items[*i].entries[*e].0), "at": sh.pt(p)}),+ };+ items.push(v);+ }+ let has_junction = sh.items.iter().any(|it| it.t == 'J' && same(it.at, p, tol));+ let all = nets(&sh, &g);+ // map groups to their nets by a member pin/label, simplest by recomputing per group+ let mut out_nets = Vec::new();+ for gr in &groups {+ let members: Vec<usize> = (0..g.nodes.len()).filter(|i| g.group[*i] == *gr).collect();+ let pins: Vec<String> = members.iter().filter_map(|i| if let Node::Pin(j) = g.nodes[*i] { Some(format!("{}.{}", sh.pins[j].r, sh.pins[j].num)) } else { None }).collect();+ let wires: Vec<String> = members.iter().filter_map(|i| if let Node::Wire(j) = g.nodes[*i] { Some(id_of(&sh.items[j].key)) } else { None }).collect();+ if let Some(n) = all.iter().find(|n| n["wires"].as_array().map(|a| a.iter().any(|w| wires.contains(&st(w)))).unwrap_or(false) || n["pins"].as_array().map(|a| a.iter().any(|x| pins.contains(&st(x)))).unwrap_or(false)) {+ out_nets.push(n.clone());+ }+ }+ let mut r = json!({"success": true, "sheet": sheet, "units": "mm", "items": items, "nets": out_nets,+ "crossingWithoutJunction": interior_wires >= 2 && !has_junction,+ "_hint": "One sheet only: a net with leavesSheet:true continues through a power port, port or sheet entry (altium_netlist gives the compiled net). crossingWithoutJunction: two wires cross here without joining; add a dot with altium_sch_junction if they should."});+ if items.is_empty() {+ // the nearest connectable point+ let mut best: Option<(f64, P)> = None;+ let mut cand: Vec<P> = sh.pins.iter().map(|p| p.at).collect();+ for it in &sh.items { match it.t { 'W' => { cand.extend(it.pts.iter().cloned()); } 'N' | 'O' | 'J' | 'X' => cand.push(it.at), 'P' => cand.extend(port_ends(it)), _ => {} } }+ for c in cand { let d = (((c.0 - p.0) as f64).powi(2) + ((c.1 - p.1) as f64).powi(2)).sqrt(); if best.map(|b| d < b.0).unwrap_or(true) { best = Some((d, c)); } }+ if let Some((_, c)) = best { r["nearest"] = sh.pt(c); }+ }+ r+}++/// How many wiring arms meet at a point: a wire end counts one, a wire passing through counts two, a pin one.+fn arms(sh: &Sheet, p: P) -> usize {+ let tol = sh.tol();+ let mut n = 0;+ for it in sh.items.iter().filter(|it| it.t == 'W') {+ for (a, b) in segs(it) {+ let (on, inside) = on_seg(p, a, b, tol);+ if inside { n += 2; } else if on && (same(a, p, tol) || same(b, p, tol)) { n += 1; }+ }+ // an inner vertex of a polyline was counted twice (end of one segment, start of the next): one arm each, right+ }+ n + sh.pins.iter().filter(|q| same(q.at, p, tol)).count()+}++/// altium_sch_junction {sheet, points?, remove?, dryRun, save}+pub fn junction(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let tol = sh.tol();+ let mut ops = Vec::new();+ let (mut planned, mut skipped, mut not_needed, mut removed) = (vec![], vec![], vec![], vec![]);+ for v in args.get("points").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let Some(m) = pts_arg(&v) else { return bad("points: [[x, y], ...] mm") };+ let p = (sh.raw(m.0), sh.raw(m.1));+ if sh.items.iter().any(|it| it.t == 'J' && same(it.at, p, tol)) { skipped.push(sh.pt(p)); continue; }+ if arms(&sh, p) < 3 { not_needed.push(sh.pt(p)); }+ ops.push(format!("J|{}|{}", p.0, p.1));+ planned.push(sh.pt(p));+ }+ for v in args.get("remove").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let hit = if let Some(id) = v.as_str() { by_id(&sh, id).filter(|(_, it)| it.t == 'J').map(|(_, it)| it) }+ else { pts_arg(&v).and_then(|m| { let p = (sh.raw(m.0), sh.raw(m.1)); sh.items.iter().find(|it| it.t == 'J' && same(it.at, p, tol)) }) };+ match hit { Some(it) => { ops.push(format!("D|{}", it.key)); removed.push(json!(id_of(&it.key))); } None => return json!({"success": false, "errorCode": "not_found", "error": format!("no junction {v}")}) }+ }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "skipped": skipped, "notNeeded": not_needed}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res[..planned.len().min(res.len())]);+ let added: Vec<Value> = ids.iter().zip(planned.iter()).map(|(i, a)| json!({"id": i, "at": a})).collect();+ let bad_steps = failed(&res);+ json!({"success": bad_steps.is_empty(), "sheet": sheet, "added": added, "removed": removed, "skipped": skipped, "notNeeded": not_needed, "failed": bad_steps, "saved": maybe_save(args, &sheet),+ "_hint": "notNeeded dots are legal but join nothing extra (fewer than three wiring arms meet there)."})+}++/// altium_sch_bus {sheet, points, label?, dryRun, save}+pub fn bus(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let pts: Vec<P> = args.get("points").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1))).collect();+ if pts.len() < 2 { return bad("points: at least two [x, y] mm"); }+ let mut ops = vec![format!("B|{}", raw_pts(&sh, &pts))];+ let label = args.get("label").and_then(|v| v.as_str()).map(clean);+ if let Some(l) = &label { ops.push(format!("N|{l}|{}|{}|{}|", pts[0].0, pts[0].1, if pts[0].0 == pts[1].0 { 1 } else { 0 })); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "points": pts.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "label": label}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res);+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "ids": ids.first().cloned().into_iter().collect::<Vec<_>>(),+ "label": label.map(|t| json!({"id": ids.get(1).cloned(), "text": t})), "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Altium draws a bus as one polyline (one id). A bus carries the nets its label names; each member wire needs its own label: altium_sch_connect_to_bus does the wires, entries and labels."})+}++fn on_bus(sh: &Sheet, p: P) -> bool { let tol = sh.tol(); sh.items.iter().filter(|it| it.t == 'B').any(|b| segs(b).iter().any(|(x, y)| on_seg(p, *x, *y, tol).0)) }++/// altium_sch_bus_entry {sheet, entries:[{at, direction}], dryRun, save}+pub fn bus_entry(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let step = sh.raw(2.54);+ let mut ops = Vec::new();+ let mut plan = Vec::new();+ for e in args.get("entries").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let Some(m) = e.get("at").and_then(pts_arg) else { return bad("entries: [{at: [x, y] mm, direction}]") };+ let a = (sh.raw(m.0), sh.raw(m.1));+ let (sx, sy) = match e.get("direction").and_then(|v| v.as_str()).unwrap_or("down-right") {+ "up-right" => (1, 1), "down-right" => (1, -1), "up-left" => (-1, 1), "down-left" => (-1, -1),+ o => return bad(format!("direction {o}: up-right, down-right, up-left or down-left")),+ };+ let end = (a.0 + sx * step, a.1 + sy * step);+ ops.push(format!("E|{}|{}|{}|{}", a.0, a.1, end.0, end.1));+ plan.push((a, end));+ }+ if plan.is_empty() { return bad("entries is required"); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "entries": plan.iter().map(|(a, e)| json!({"at": sh.pt(*a), "end": sh.pt(*e), "onBus": on_bus(&sh, *e)})).collect::<Vec<_>>()}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res);+ let added: Vec<Value> = plan.iter().zip(ids.iter()).map(|((a, e), id)| json!({"id": id, "at": sh.pt(*a), "end": sh.pt(*e), "onBus": on_bus(&sh, *e)})).collect();+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "added": added, "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "end is the bus side (2.54 mm diagonal). An entry whose end is not on a bus (onBus false) is unconnected in ERC: move it or extend the bus with altium_sch_bus."})+}++/// Split a polyline at p on segment s: (first half, second half).+pub fn split_at(pts: &[P], s: usize, p: P) -> (Vec<P>, Vec<P>) {+ let mut a: Vec<P> = pts[..=s].to_vec(); a.push(p);+ let mut b = vec![p]; b.extend_from_slice(&pts[s + 1..]);+ (a, b)+}++/// altium_sch_split_wire {sheet, at, id?, junction?, dryRun, save}+pub fn split_wire(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let Some(m) = args.get("at").and_then(pts_arg) else { return bad("at: [x, y] mm is required") };+ let p = (sh.raw(m.0), sh.raw(m.1));+ let tol = sh.tol();+ let want = args.get("id").and_then(|v| v.as_str());+ let mut hits = Vec::new();+ for it in sh.items.iter().filter(|it| it.t == 'W' && want.map(|w| id_of(&it.key) == w).unwrap_or(true)) {+ let n = it.pts.len();+ if same(it.pts[0], p, tol) || same(it.pts[n - 1], p, tol) { continue; }+ if let Some(s) = segs(it).iter().position(|(a, b)| on_seg(p, *a, *b, tol).0) { hits.push((it, s)); }+ }+ let (it, s) = match hits.len() {+ 0 => return json!({"success": false, "errorCode": "not_on_wire", "error": "no wire passes through that point (an end does not count: a branch can end on a wire end already)"}),+ 1 => hits[0],+ _ => return json!({"success": false, "errorCode": "ambiguous", "error": "several wires pass through that point: give id", "ids": hits.iter().map(|(i, _)| id_of(&i.key)).collect::<Vec<_>>()}),+ };+ let (a, b) = split_at(&it.pts, s, p);+ let jn = args.get("junction").and_then(|v| v.as_bool()) != Some(false);+ let mut ops = vec![format!("V|{}|{}", it.key, raw_pts(&sh, &a)), format!("W|{}", raw_pts(&sh, &b))];+ if jn { ops.push(format!("J|{}|{}", p.0, p.1)); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "first": a.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>(), "second": b.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>()}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res);+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "ids": ids.iter().take(2).collect::<Vec<_>>(), "junction": if jn { json!({"id": ids.get(2), "at": sh.pt(p)}) } else { Value::Null },+ "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Both halves get new ids (Altium ids follow geometry). Wire the new branch to the cut point."})+}++/// altium_sch_delete_wire {sheet, ids?, from?+to?, at?, dryRun, save}+pub fn delete_wire(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let tol = sh.tol();+ let mut dead: Vec<usize> = Vec::new();+ for v in args.get("ids").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ match v.as_str().and_then(|id| by_id(&sh, id)) { Some((i, it)) if matches!(it.t, 'W' | 'B') => dead.push(i), _ => return json!({"success": false, "errorCode": "not_found", "error": format!("no wire or bus {v}: read ids with altium_sch_items")}) }+ }+ if let (Some(f), Some(t)) = (args.get("from").and_then(pts_arg), args.get("to").and_then(pts_arg)) {+ let (f, t) = ((sh.raw(f.0), sh.raw(f.1)), (sh.raw(t.0), sh.raw(t.1)));+ let hit = sh.items.iter().position(|it| matches!(it.t, 'W' | 'B') && { let (a, b) = (it.pts[0], it.pts[it.pts.len() - 1]); (same(a, f, tol) && same(b, t, tol)) || (same(a, t, tol) && same(b, f, tol)) });+ match hit { Some(i) => dead.push(i), None => return json!({"success": false, "errorCode": "not_found", "error": "no wire with exactly those two ends"}) }+ }+ if let Some(a) = args.get("at").and_then(pts_arg) {+ let p = (sh.raw(a.0), sh.raw(a.1));+ dead.extend(sh.items.iter().enumerate().filter(|(_, it)| matches!(it.t, 'W' | 'B') && segs(it).iter().any(|(x, y)| on_seg(p, *x, *y, tol).0)).map(|(i, _)| i));+ }+ dead.sort(); dead.dedup();+ if dead.is_empty() { return bad("give ids, from and to, or at"); }+ // junctions that no longer join three or more arms once these wires are gone+ let mut after = sh.clone();+ after.items = sh.items.iter().enumerate().filter(|(i, _)| !dead.contains(i)).map(|(_, it)| it.clone()).collect();+ // only dots that sat on a deleted wire: a dot left for a future branch elsewhere stays+ let on_dead = |p: P| dead.iter().any(|i| segs(&sh.items[*i]).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0));+ let orphan: Vec<&Item> = after.items.iter().filter(|it| it.t == 'J' && on_dead(it.at) && arms(&after, it.at) < 3).collect();+ let mut ops: Vec<String> = dead.iter().map(|i| format!("D|{}", sh.items[*i].key)).collect();+ ops.extend(orphan.iter().map(|j| format!("D|{}", j.key)));+ let deleted: Vec<Value> = dead.iter().map(|i| { let it = &sh.items[*i]; json!({"id": id_of(&it.key), "from": sh.pt(it.pts[0]), "to": sh.pt(it.pts[it.pts.len() - 1])}) }).collect();+ let jr: Vec<Value> = orphan.iter().map(|j| sh.pt(j.at)).collect();+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "deleted": deleted, "junctionsRemoved": jr}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "deleted": deleted, "junctionsRemoved": jr, "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "An Altium wire is one polyline: deleting it removes all its segments. To cut one segment out, split it first (altium_sch_split_wire)."})+}++/// altium_sch_edit_label {sheet, edits:[{id | text (+at) | net, rotation?, to?, by?, rename?}], dryRun, save}+pub fn edit_label(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let tol = sh.tol();+ let mut ops = Vec::new();+ let mut plan = Vec::new();+ let mut failed_edits = Vec::new();+ for e in args.get("edits").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let picked: Vec<&Item> = if let Some(id) = e.get("id").and_then(|v| v.as_str()) {+ by_id(&sh, id).map(|(_, it)| it).filter(|it| it.t == 'N').into_iter().collect()+ } else if let Some(t) = e.get("text").and_then(|v| v.as_str()) {+ let at = e.get("at").and_then(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1)));+ sh.items.iter().filter(|it| it.t == 'N' && it.text == t && at.map(|a| same(a, it.at, tol)).unwrap_or(true)).collect()+ } else if let Some(n) = e.get("net").and_then(|v| v.as_str()) {+ sh.items.iter().filter(|it| it.t == 'N' && it.text.eq_ignore_ascii_case(n)).collect()+ } else { vec![] };+ if picked.is_empty() { failed_edits.push(json!({"edit": e, "error": "no label matches"})); continue; }+ if e.get("to").is_some() && picked.len() > 1 { failed_edits.push(json!({"edit": e, "error": "to moves one label only; use by for several"})); continue; }+ for it in picked {+ let mut at = it.at;+ if let Some(m) = e.get("to").and_then(pts_arg) { at = (sh.raw(m.0), sh.raw(m.1)); }+ if let Some(m) = e.get("by").and_then(pts_arg) { at = (at.0 + sh.raw(m.0), at.1 + sh.raw(m.1)); }+ let rot = e.get("rotation").and_then(|v| v.as_i64()).map(|r| ((r.rem_euclid(360)) / 90).to_string()).unwrap_or_default();+ let text = e.get("rename").and_then(|v| v.as_str()).map(clean).unwrap_or_default();+ ops.push(format!("L|{}|{}|{}|{}|{}", it.key, text, at.0, at.1, rot));+ plan.push(json!({"was": id_of(&it.key), "text": if text.is_empty() { it.text.clone() } else { text.clone() }, "at": sh.pt(at),+ "rotation": if rot.is_empty() { it.rot * 90 } else { rot.parse::<i64>().unwrap_or(0) * 90 }}));+ }+ }+ if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edit matched a label", "failed": failed_edits}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "edited": plan, "failed": failed_edits}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res);+ let edited: Vec<Value> = plan.into_iter().zip(ids).map(|(mut p, id)| { p["id"] = id; p }).collect();+ let fails = failed(&res);+ json!({"success": fails.is_empty() && failed_edits.is_empty(), "sheet": sheet, "edited": edited, "failed": failed_edits, "stepsFailed": fails, "saved": maybe_save(args, &sheet),+ "_hint": "A label renamed joins the net of its new name across the sheet; a label moved off its wire stops naming it: check with altium_sch_pins or altium_compile."})+}++/// Altium's text justification from "left bottom" style words.+pub fn justification(s: &str) -> i64 {+ let w = s.to_lowercase();+ let h = if w.contains("right") { 2 } else if w.contains("center") || w.contains("centre") { 1 } else { 0 };+ let v = if w.contains("top") { 2 } else if w.contains("middle") || (w.contains("center") && !w.contains("left") && !w.contains("right") && w.split_whitespace().count() > 1) { 1 } else { 0 };+ v * 3 + h+}++/// altium_sch_text {sheet, texts:[{text, at, rotation?, sizeMm?, justify?, bold?, italic?}], dryRun, save}+pub fn text(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let mut ops = Vec::new();+ let mut plan = Vec::new();+ for t in args.get("texts").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let Some(m) = t.get("at").and_then(pts_arg) else { return bad("texts: [{text, at: [x, y] mm, ...}]") };+ let s = clean(&st(&t["text"]));+ if s.is_empty() { return bad("each text needs text"); }+ let at = (sh.raw(m.0), sh.raw(m.1));+ // Altium sizes text in points: 10 pt is about 2.54 mm tall+ let pt = ((t.get("sizeMm").and_then(|v| v.as_f64()).unwrap_or(1.27) / 2.54 * 10.0).round() as i64).max(1);+ let rot = t.get("rotation").and_then(|v| v.as_i64()).unwrap_or(0).rem_euclid(360) / 90;+ let b = |k: &str| if t.get(k).and_then(|v| v.as_bool()) == Some(true) { "1" } else { "0" };+ let j = t.get("justify").and_then(|v| v.as_str()).map(|s| justification(s).to_string()).unwrap_or_default();+ ops.push(format!("T|{s}|{}|{}|{rot}|{pt}|{}|{}|{j}", at.0, at.1, b("bold"), b("italic")));+ plan.push(json!({"text": s, "at": sh.pt(at)}));+ }+ if plan.is_empty() { return bad("texts is required"); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "added": plan}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let added: Vec<Value> = plan.into_iter().zip(new_ids(&res)).map(|(mut p, id)| { p["id"] = id; p }).collect();+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "added": added, "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Free text has no electrical meaning: net names are labels (altium_sch_connect). Altium's text is one line; sizes are converted to points (10 pt is about 2.54 mm)."})+}++fn pin_of<'a>(sh: &'a Sheet, key: &str) -> Option<&'a Pin> {+ let (r, n) = key.rsplit_once('.')?;+ sh.pins.iter().find(|p| p.r.eq_ignore_ascii_case(r) && p.num.eq_ignore_ascii_case(n))+ .or_else(|| sh.pins.iter().find(|p| p.r.eq_ignore_ascii_case(r) && p.name.eq_ignore_ascii_case(n)))+}++/// An orthogonal route from a to b through waypoints: straight when aligned, else one turn per leg; the first leg+/// along h (horizontal) or v.+pub fn route(a: P, b: P, via: &[P], first_h: bool) -> Vec<P> {+ let mut pts = vec![a];+ let mut cur = a;+ let mut h = first_h;+ for &t in via.iter().chain(std::iter::once(&b)) {+ if cur.0 != t.0 && cur.1 != t.1 { let corner = if h { (t.0, cur.1) } else { (cur.0, t.1) }; pts.push(corner); }+ pts.push(t);+ h = !h;+ cur = t;+ }+ pts.dedup();+ pts+}++/// Where existing wires' ends land in the middle of the new route, or the route's ends land in the middle of an+/// existing wire: a T, which wants a junction dot.+pub fn tees(sh: &Sheet, route: &[P]) -> Vec<P> {+ let tol = sh.tol();+ let mut out = Vec::new();+ let rs: Vec<(P, P)> = route.windows(2).map(|w| (w[0], w[1])).collect();+ for it in sh.items.iter().filter(|it| it.t == 'W') {+ for e in [it.pts[0], it.pts[it.pts.len() - 1]] { if rs.iter().any(|(a, b)| on_seg(e, *a, *b, tol).1) { out.push(e); } }+ for e in [route[0], route[route.len() - 1]] { if segs(it).iter().any(|(a, b)| on_seg(e, *a, *b, tol).1) { out.push(e); } }+ }+ out.sort(); out.dedup();+ out+}++/// altium_sch_connect_pins {sheet, pairs:[{from, to, first?, via?}], dryRun, save}+pub fn connect_pins(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let mut ops = Vec::new();+ let mut routes = Vec::new();+ let mut fails = Vec::new();+ let mut dots: Vec<P> = Vec::new();+ for pr in args.get("pairs").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let (f, t) = (st(&pr["from"]), st(&pr["to"]));+ let (Some(a), Some(b)) = (pin_of(&sh, &f), pin_of(&sh, &t)) else { fails.push(json!({"from": f, "to": t, "error": "pin not found on this sheet (Ref.Pin, by number then name)"})); continue; };+ let first_h = match pr.get("first").and_then(|v| v.as_str()) { Some("h") => true, Some("v") => false, _ => a.dir % 2 == 0 };+ let via: Vec<P> = pr.get("via").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(pts_arg).map(|m| (sh.raw(m.0), sh.raw(m.1))).collect();+ let r = route(a.at, b.at, &via, first_h);+ dots.extend(tees(&sh, &r));+ ops.push(format!("W|{}", raw_pts(&sh, &r)));+ routes.push(json!({"from": f, "to": t, "points": r.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>()}));+ }+ dots.sort(); dots.dedup();+ let n_routes = ops.len();+ ops.extend(dots.iter().map(|p| format!("J|{}|{}", p.0, p.1)));+ if routes.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no pair could be wired", "failed": fails}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "routes": routes, "junctionsAdded": dots.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "failed": fails}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res[..n_routes.min(res.len())]);+ let routes: Vec<Value> = routes.into_iter().zip(ids).map(|(mut r, id)| { r["ids"] = json!([id]); r }).collect();+ json!({"success": fails.is_empty() && failed(&res).is_empty(), "sheet": sheet, "wired": routes.len(), "routes": routes,+ "junctionsAdded": dots.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>(), "failed": fails, "stepsFailed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Each route is one Altium wire (a polyline). Routes do not avoid bodies or other wires: a leg along another wire merges the nets. Check with altium_sch_pins (connectedPins) or altium_compile."})+}++/// altium_sch_connect_to_bus {sheet, pins, bus?, members? | prefix+start, entry?, busLabel?, dryRun, save}+pub fn connect_to_bus(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let buses: Vec<&Item> = sh.items.iter().filter(|it| it.t == 'B').collect();+ let bus = match args.get("bus").and_then(|v| v.as_str()) {+ Some(id) => match by_id(&sh, id) { Some((_, it)) if it.t == 'B' => it, _ => return json!({"success": false, "errorCode": "not_found", "error": format!("no bus {id}")}) },+ None if buses.len() == 1 => buses[0],+ None => return json!({"success": false, "errorCode": if buses.is_empty() { "no_bus" } else { "ambiguous" }, "error": if buses.is_empty() { "no bus on this sheet: draw one with altium_sch_bus" } else { "several buses: give bus (an id from altium_sch_items)" }}),+ };+ let pins: Vec<String> = args.get("pins").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().map(st).collect();+ if pins.is_empty() { return bad("pins: [\"U1.1\", ...] in member order"); }+ let members: Vec<String> = match args.get("members").and_then(|v| v.as_array()) {+ Some(m) => m.iter().map(|x| clean(&st(x))).collect(),+ None => { let pre = args.get("prefix").and_then(|v| v.as_str()).unwrap_or("D"); let s0 = args.get("start").and_then(|v| v.as_i64()).unwrap_or(0); (0..pins.len()).map(|i| format!("{pre}{}", s0 + i as i64)).collect() }+ };+ if members.len() != pins.len() { return bad("members must name one member per pin"); }+ let step = sh.raw(2.54);+ let tol = sh.tol();+ let mut ops = Vec::new();+ let mut plan = Vec::new();+ let mut fails = Vec::new();+ for (k, key) in pins.iter().enumerate() {+ let Some(p) = pin_of(&sh, key) else { fails.push(json!({"pin": key, "error": "pin not found"})); continue; };+ // the bus segment beside the pin: a vertical one spanning its height or a horizontal one spanning its x+ let seg = segs(bus).into_iter().find(|(a, b)| (a.0 == b.0 && p.at.1 >= a.1.min(b.1) - step && p.at.1 <= a.1.max(b.1) + step) || (a.1 == b.1 && p.at.0 >= a.0.min(b.0) - step && p.at.0 <= a.0.max(b.0) + step));+ let Some((a, b)) = seg else { fails.push(json!({"pin": key, "error": "entry_off_bus: no bus segment beside this pin; extend the bus with altium_sch_bus"})); continue; };+ let vertical = a.0 == b.0;+ let lean = args.get("entry").and_then(|v| v.as_str()).unwrap_or(if vertical { "down" } else { "right" });+ let (wire_end, entry_end) = if vertical {+ let side = if p.at.0 < a.0 { -1 } else { 1 };+ let dy = if lean == "up" { step } else { -step };+ ((a.0 + side * step, p.at.1), (a.0, p.at.1 + dy))+ } else {+ let side = if p.at.1 < a.1 { -1 } else { 1 };+ let dx = if lean == "left" { -step } else { step };+ ((p.at.0, a.1 + side * step), (p.at.0 + dx, a.1))+ };+ if !segs(bus).iter().any(|(x, y)| on_seg(entry_end, *x, *y, tol).0) { fails.push(json!({"pin": key, "error": "entry_off_bus: the entry would miss the bus; extend it with altium_sch_bus"})); continue; }+ let wire = route(p.at, wire_end, &[], vertical);+ ops.push(format!("W|{}", raw_pts(&sh, &wire)));+ ops.push(format!("E|{}|{}|{}|{}", wire_end.0, wire_end.1, entry_end.0, entry_end.1));+ // the member label on the wire, just before the entry+ let lab = wire_end;+ ops.push(format!("N|{}|{}|{}|{}|{}", members[k], lab.0, lab.1, if vertical { 0 } else { 1 }, if vertical && p.at.0 < a.0 { "2" } else { "" }));+ plan.push(json!({"pin": key, "member": members[k], "wire": wire.iter().map(|q| sh.pt(*q)).collect::<Vec<_>>(), "entry": [sh.pt(wire_end), sh.pt(entry_end)]}));+ }+ let bus_label = args.get("busLabel").and_then(|v| v.as_str()).map(clean);+ if let Some(l) = &bus_label { ops.push(format!("N|{l}|{}|{}|{}|", bus.pts[0].0, bus.pts[0].1, if bus.pts[0].0 == bus.pts[1].0 { 1 } else { 0 })); }+ if plan.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no pin could be connected", "failed": fails}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "connected": plan, "busLabel": bus_label, "failed": fails}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res);+ let connected: Vec<Value> = plan.into_iter().enumerate().map(|(i, mut p)| { p["wireId"] = ids.get(3 * i).cloned().unwrap_or(Value::Null); p["entryId"] = ids.get(3 * i + 1).cloned().unwrap_or(Value::Null); p }).collect();+ json!({"success": fails.is_empty() && failed(&res).is_empty(), "sheet": sheet, "connected": connected, "busLabel": bus_label, "failed": fails, "stepsFailed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Each pin got a wire to 2.54 mm short of the bus, a 45-degree entry onto it and its member label. The bus's own label (busLabel, e.g. D[0..7]) must name every member. Check with altium_compile."})+}++/// altium_sch_move_region {sheet, box, by, wires?, labels?, junctions?, dryRun, save}+pub fn move_region(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let bx: Vec<f64> = args.get("box").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();+ let Some(by) = args.get("by").and_then(pts_arg) else { return bad("by: [dx, dy] mm is required") };+ if bx.len() != 4 { return bad("box: [x1, y1, x2, y2] mm is required"); }+ let (x0, x1) = (sh.raw(bx[0].min(bx[2])), sh.raw(bx[0].max(bx[2])));+ let (y0, y1) = (sh.raw(bx[1].min(bx[3])), sh.raw(bx[1].max(bx[3])));+ let inside = |p: P| p.0 >= x0 && p.0 <= x1 && p.1 >= y0 && p.1 <= y1;+ let (dx, dy) = (sh.raw(by.0), sh.raw(by.1));+ let flag = |k: &str| args.get(k).and_then(|v| v.as_bool()) != Some(false);+ let mut ops = Vec::new();+ let mut moved: BTreeMap<&str, Vec<Value>> = BTreeMap::new();+ for c in sh.comps.iter().filter(|c| inside(c.at)) { ops.push(format!("C|{}|{dx}|{dy}", c.r)); moved.entry("parts").or_default().push(json!(c.r)); }+ for it in &sh.items {+ let (kind, on) = match it.t { 'W' => ("wires", flag("wires")), 'B' => ("buses", flag("wires")), 'E' => ("busEntries", flag("wires")), 'N' | 'P' | 'O' => ("labels", flag("labels")), 'T' => ("texts", flag("labels")),+ 'J' => ("junctions", flag("junctions")), 'X' => ("noConnects", flag("junctions")), 'S' => ("sheets", true), _ => continue };+ if !on { continue; }+ if matches!(it.t, 'W' | 'B') {+ if !it.pts.iter().any(|p| inside(*p)) { continue; }+ let np: Vec<P> = it.pts.iter().map(|p| if inside(*p) { (p.0 + dx, p.1 + dy) } else { *p }).collect();+ ops.push(format!("V|{}|{}", it.key, raw_pts(&sh, &np)));+ } else {+ if !inside(it.at) { continue; }+ ops.push(format!("G|{}|{dx}|{dy}", it.key));+ }+ moved.entry(kind).or_default().push(json!(id_of(&it.key)));+ }+ if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "nothing inside the box"}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "moved": moved}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "moved": moved, "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Ids listed are the items' ids before the move; read new ones with altium_sch_items. Wires with one end inside stretched; move by a pure dx or dy to keep them straight."})+}++/// altium_sch_fix_connectivity {sheet, toleranceMm?, dryRun (default true), save}+pub fn fix_connectivity(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let tol = sh.tol();+ let reach = sh.raw(args.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.5));+ let dry_run = args.get("dryRun").and_then(|v| v.as_bool()) != Some(false);+ // targets a dangling end may snap onto: pins, labels, ports, power, sheet entries, other wires' ends+ let mut targets: Vec<(P, &'static str, String)> = sh.pins.iter().map(|p| (p.at, "pin", format!("{}.{}", p.r, p.num))).collect();+ for it in &sh.items {+ match it.t {+ 'N' | 'O' => targets.push((it.at, kind_name(it.t), id_of(&it.key))),+ 'P' => for e in port_ends(it) { targets.push((e, "port", id_of(&it.key))) },+ 'S' => for (n, side, dist, _) in &it.entries { targets.push((entry_point(it, *side, *dist), "sheetPin", format!("{}/{n}", id_of(&it.key)))) },+ _ => {}+ }+ }+ let mut moves = Vec::new();+ let mut unresolved = Vec::new();+ let mut ops = Vec::new();+ for (wi, w) in sh.items.iter().enumerate().filter(|(_, it)| it.t == 'W') {+ let mut np = w.pts.clone();+ let mut changed = false;+ for end in [0, w.pts.len() - 1] {+ let p = w.pts[end];+ let joined = targets.iter().any(|(q, _, _)| same(*q, p, tol))+ || sh.items.iter().enumerate().any(|(j, o)| j != wi && match o.t { 'W' | 'B' => segs(o).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0), 'J' | 'X' | 'E' => same(o.at, p, tol) || same(o.corner, p, tol), _ => false });+ if joined { continue; }+ let mut best: Option<(f64, P, &str, String)> = None;+ for (q, k, id) in &targets { let d = (((q.0 - p.0) as f64).powi(2) + ((q.1 - p.1) as f64).powi(2)).sqrt(); if d <= reach as f64 && best.as_ref().map(|b| d < b.0).unwrap_or(true) { best = Some((d, *q, k, id.clone())); } }+ for (j, o) in sh.items.iter().enumerate().filter(|(j, o)| *j != wi && o.t == 'W') {+ let _ = j;+ for q in [o.pts[0], o.pts[o.pts.len() - 1]] { let d = (((q.0 - p.0) as f64).powi(2) + ((q.1 - p.1) as f64).powi(2)).sqrt(); if d <= reach as f64 && best.as_ref().map(|b| d < b.0).unwrap_or(true) { best = Some((d, q, "wire", id_of(&o.key))); } }+ }+ match best {+ Some((_, q, k, id)) => {+ np[end] = q; changed = true;+ let nb = if end == 0 { np.get(1) } else { np.get(np.len().saturating_sub(2)) }.copied().unwrap_or(q);+ moves.push(json!({"wireId": id_of(&w.key), "from": sh.pt(p), "to": sh.pt(q), "onto": {"kind": k, "id": id}, "diagonal": nb.0 != q.0 && nb.1 != q.1}));+ }+ None => unresolved.push(sh.pt(p)),+ }+ }+ if changed { ops.push(format!("V|{}|{}", w.key, raw_pts(&sh, &np))); }+ }+ if dry_run || ops.is_empty() { return json!({"success": true, "dryRun": dry_run, "sheet": sheet, "moves": moves, "unresolved": unresolved,+ "_hint": "dryRun defaults to true: read the moves, then call again with dryRun:false. unresolved ends have nothing within toleranceMm."}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ json!({"success": failed(&res).is_empty(), "sheet": sheet, "moves": moves, "unresolved": unresolved, "failed": failed(&res), "saved": maybe_save(args, &sheet),+ "_hint": "Snapped ends now touch their targets; diagonal:true wires are no longer horizontal or vertical. Check with altium_compile."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn wire(pts: &[P]) -> Item { Item { t: 'W', key: format!("W:{pts:?}"), pts: pts.to_vec(), ..Default::default() } }+ fn item(t: char, at: P, text: &str) -> Item { Item { t, key: format!("{t}:{at:?}:{text}"), at, text: text.into(), ..Default::default() } }+ fn pin(r: &str, n: &str, at: P) -> Pin { Pin { r: r.into(), num: n.into(), name: n.into(), at, ..Default::default() } }+ fn sheet(items: Vec<Item>, pins: Vec<Pin>) -> Sheet { Sheet { k: 1000.0, items, pins, ..Default::default() } } // 1 raw unit = 1 mil++ #[test]+ fn wires_join_at_ends_and_tees_but_not_where_they_cross() {+ // U1.1 -- wire -- R1.1, a T from the middle down to C1.1, and a crossing wire with no dot+ let sh = sheet(vec![wire(&[(0, 0), (1000, 0)]), wire(&[(500, 0), (500, -500)]), wire(&[(300, 300), (300, -300)])],+ vec![pin("U1", "1", (0, 0)), pin("R1", "1", (1000, 0)), pin("C1", "1", (500, -500)), pin("D1", "1", (300, 300))]);+ let g = graph(&sh);+ let ns = nets(&sh, &g);+ let net = ns.iter().find(|n| n["pins"].as_array().unwrap().contains(&json!("U1.1"))).unwrap();+ let pins: Vec<String> = net["pins"].as_array().unwrap().iter().map(st).collect();+ assert!(pins.contains(&"R1.1".into()) && pins.contains(&"C1.1".into()));+ assert!(!pins.contains(&"D1.1".into()), "a crossing without a dot does not join");+ // with a dot at the crossing it does+ let mut sh2 = sh.clone();+ sh2.items.push(item('J', (300, 0), ""));+ let n2 = nets(&sh2, &graph(&sh2));+ assert!(n2.iter().any(|n| { let p = n["pins"].as_array().unwrap(); p.contains(&json!("D1.1")) && p.contains(&json!("U1.1")) }));+ }++ #[test]+ fn labels_with_the_same_text_are_one_net_and_name_it() {+ let sh = sheet(vec![wire(&[(0, 0), (500, 0)]), wire(&[(0, 1000), (500, 1000)]), item('N', (200, 0), "SDA"), item('N', (200, 1000), "SDA")],+ vec![pin("U1", "5", (0, 0)), pin("U2", "3", (500, 1000))]);+ let ns = nets(&sh, &graph(&sh));+ let sda: Vec<&Value> = ns.iter().filter(|n| n["name"] == "SDA").collect();+ assert_eq!(sda.len(), 1);+ assert_eq!(sda[0]["pins"].as_array().unwrap().len(), 2);+ }++ #[test]+ fn a_route_turns_once_and_tees_are_found() {+ assert_eq!(route((0, 0), (100, 0), &[], true), vec![(0, 0), (100, 0)]);+ assert_eq!(route((0, 0), (100, 50), &[], true), vec![(0, 0), (100, 0), (100, 50)]);+ assert_eq!(route((0, 0), (100, 50), &[], false), vec![(0, 0), (0, 50), (100, 50)]);+ // an existing wire ends on the new route's middle: a T+ let sh = sheet(vec![wire(&[(50, 0), (50, -100)])], vec![]);+ assert_eq!(tees(&sh, &[(0, 0), (100, 0)]), vec![(50, 0)]);+ }++ #[test]+ fn splitting_keeps_every_vertex() {+ let (a, b) = split_at(&[(0, 0), (100, 0), (100, 100)], 1, (100, 40));+ assert_eq!(a, vec![(0, 0), (100, 0), (100, 40)]);+ assert_eq!(b, vec![(100, 40), (100, 100)]);+ }++ #[test]+ fn arms_count_ends_middles_and_pins() {+ let sh = sheet(vec![wire(&[(0, 0), (100, 0)]), wire(&[(50, 0), (50, 100)])], vec![]);+ assert_eq!(arms(&sh, (50, 0)), 3);+ assert_eq!(arms(&sh, (0, 0)), 1);+ }++ #[test]+ fn justification_words() {+ assert_eq!(justification("left bottom"), 0);+ assert_eq!(justification("right top"), 8);+ assert_eq!(justification("center"), 1);+ }++ #[test]+ fn units_and_ids() {+ let sh = Sheet { k: 10_000_000.0, ..Default::default() };+ assert_eq!(sh.raw(25.4), 10_000_000);+ assert_eq!(sh.mm(10_000_000), 25.4);+ assert!(id_of("W:0,0,10,0").starts_with("wire-"));+ assert_ne!(id_of("W:0,0,10,0"), id_of("W:0,0,10,1"));+ }+}
bridge-rs/src/verbs.rs+71−1@@ -28,7 +28,7 @@ pub const KNOWN: &[&str] = &[ "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo", "animate_view", "foreground", // outputs / project- "compile", "run_erc", "run_drc", "run_outjob", "export_gerber", "export_bom", "export_step", "bom", "variants", "workspace_search", "workspace_place", "sheet_params", "sch_place_part", "sch_swap_part", "sch_connect", "sch_edit", "annotate", "doc_params", "update_pcb", "export_pdf", "sch_zoom", "autoroute",+ "compile", "run_erc", "run_drc", "run_outjob", "export_gerber", "export_bom", "export_step", "bom", "variants", "workspace_search", "workspace_place", "sheet_params", "sch_place_part", "sch_swap_part", "sch_connect", "sch_edit", "sch_items", "sch_pins", "sch_trace_point", "sch_junction", "sch_bus", "sch_bus_entry", "sch_split_wire", "sch_delete_wire", "sch_edit_label", "sch_text", "sch_connect_pins", "sch_connect_to_bus", "sch_move_region", "sch_fix_connectivity", "annotate", "doc_params", "update_pcb", "export_pdf", "sch_zoom", "autoroute", "save", "test_board", "board_shape", "pcb_report", "import_kicad", "install_extension", "extension_ping", // library authoring@@ -644,6 +644,62 @@ fn describe() -> Value { &["sch_connect", "annotate", "update_pcb", "list_library"], &["Places part 1 of a multi-part component unless partId says otherwise.", "Sheet coordinates are mils from the sheet's lower-left corner; altium_schematic_data shows where the other parts are."], json!({"sheet": "C:/proj/Main.SchDoc", "library": "C:/proj/Lib.SchLib", "symbol": "TPS54202DDCR", "designator": "U2", "x": 3000, "y": 4000})),+ verb_doc("sch_items", "List a sheet's wiring items with ids and coordinates: wires, buses, bus entries, net labels (local, global, hierarchical), power ports, junctions, no-connect markers, texts and sheet symbols. Read only. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "kinds": "[wires, buses, busEntries, labels, powerPorts, junctions, noConnects, texts, sheets] (default all)"}),+ json!({"wires": "[{id, from, to}]", "buses": "[{id, from, to}]", "busEntries": "[{id, at, end}]", "labels": "[{id, text, kind: local|global|hierarchical, at, rotation}]", "powerPorts": "[{id, net, at}]", "junctions": "[{id, at}]", "noConnects": "[{id, at}]", "texts": "[{id, text, at}]", "sheets": "[{id, name, file, at, sizeMm}]", "counts": "{kind: int}"}), 120,+ "The ids feed sch_delete_wire, sch_edit_label, sch_junction and sch_edit. Parts are in schematic_data.", &["schematic_data", "sch_pins", "sch_delete_wire", "sch_edit_label"], &["A wire is one straight segment: a polyline drawn in the editor is several wires sharing ends.", "Altium items have no stable id: an id is the item's kind plus a hash of its geometry, valid until the item changes; every edit answers the new ids."], json!({"sheet": "C:/proj/Main.SchDoc", "kinds": ["wires", "labels"]})),+ verb_doc("sch_pins", "Every pin of the named parts on a sheet: its absolute position (rotation and mirror applied), number, name, electrical type, the side it leaves the body, and the wires, labels and nets touching it. Read only. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "references": "[\"U1\", \"R5\"] (default every part)", "connections": "bool, default true: add what touches each pin"}),+ json!({"pins": "[{ref, number, name, type, at: [x, y], direction: right|left|up|down as seen, hidden, touching: [{kind, id}], nets: [string], connectedPins: [Ref.Pin]}]"}), 120,+ "at is where a wire or label must land on the pin. connectedPins lists the other pins on the same copper on this sheet.", &["sch_connect_pins", "sch_connect", "schematic_data", "netlist"], &["Nets here come from this sheet's wires and labels only: netlist gives the project-wide nets.", "Hidden power pins (hidden:true) connect by name, not by wire."], json!({"sheet": "C:/proj/Main.SchDoc", "references": ["U1", "R5"]})),+ verb_doc("sch_trace_point", "Everything electrically connected at a point on a sheet: the wires, labels, pins, junctions, sheet pins and no-connect markers there, and for each net they belong to the whole net with its name. Read only. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "at": "[x, y] mm on the sheet (the tool's sheet origin, y up) (required)", "toleranceMm": "number, default 0.05"}),+ json!({"items": "[{kind, id, at}]", "nets": "[{name, pins: [Ref.Pin], labels, powerPorts, wires, leavesSheet: bool}]", "crossingWithoutJunction": "bool: two wires cross here without connecting", "nearest": "[x, y]: the nearest connectable point, when nothing is within tolerance"}), 120,+ "Read with the tool's own rules: wire ends join wires and wire middles (a T), labels and junction dots join a wire anywhere along it, pins join wire ends.", &["sch_pins", "netlist"], &["One sheet only: a net that leaves through a global, hierarchical or power label (leavesSheet:true) continues on other sheets. netlist gives the compiled net."], json!({"sheet": "C:/proj/Power.SchDoc", "at": [109.22, 73.66]})),+ verb_doc("sch_junction", "Add junction dots at points, or remove dots by id or point. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "points": "[[x, y], ...] mm: where to add dots", "remove": "[id or [x, y], ...]: dots to remove", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"added": "[{id, at}]", "removed": "[id]", "skipped": "[[x, y]]: points that already had a dot", "notNeeded": "[[x, y]]: added dots where fewer than three items meet (legal, but they join nothing extra)", "saved": "bool"}), 120,+ "The wiring verbs add the dots they need on their own; use this for a T made by hand, or to clean up.", &["sch_items", "sch_split_wire", "sch_delete_wire"], &["Items join only where their coordinates match exactly: use pin ends from sch_pins, or points on the sheet's grid."], json!({"sheet": "C:/proj/Main.SchDoc", "points": [[110.49, 60.96]]})),+ verb_doc("sch_bus", "Draw a bus as a polyline (one bus segment per pair of points), optionally with a bus label such as D[0..7] or a group {SDA SCL} at its first point. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "points": "[[x, y], [x, y], ...] mm (required)", "label": "\"D[0..7]\" or \"{SDA SCL}\": the nets the bus carries", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"ids": "[bus segment id]", "label": "{id, text} or null", "saved": "bool"}), 120,+ "A bus carries the nets its label names, and each member wire needs its own label. sch_connect_to_bus does the member wires, entries and labels for a set of pins.", &["sch_bus_entry", "sch_connect_to_bus", "sch_delete_wire", "sch_items"], &["A bus with no label carries nothing: ERC reports its members as unconnected."], json!({"sheet": "C:/proj/Main.SchDoc", "points": [[203.2, 50.8], [203.2, 101.6]], "label": "D[0..7]"})),+ verb_doc("sch_bus_entry", "Add 45-degree bus entries: the short diagonal that joins a member wire's end to a bus. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "entries": "[{at: [x, y] mm (the wire end), direction: up-right|down-right|up-left|down-left as seen (default down-right)}] (required)", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"added": "[{id, at, end: [x, y] (the bus side), onBus: bool}]", "saved": "bool"}), 120,+ "end is the bus side of each entry; onBus says whether it lands on a bus segment.", &["sch_bus", "sch_connect_to_bus", "sch_items"], &["The bus side must touch a bus and the other end a wire end, exactly, or ERC reports the entry as unconnected."], json!({"sheet": "C:/proj/Main.SchDoc", "entries": [{"at": [200.66, 63.5], "direction": "up-right"}]})),+ verb_doc("sch_split_wire", "Split the wire through a point into two wires there, with a junction dot at the cut, so a new branch can end on a wire end. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "at": "[x, y] mm on the sheet (the tool's sheet origin, y up) (required)", "id": "the wire's id, when several wires pass through the point", "junction": "bool, default true", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"ids": "[first half (keeps the wire's id), second half (new id)]", "junction": "{id, at} or null", "saved": "bool"}), 120,+ "Split a wire where a new branch should join it, then wire to the cut.", &["sch_delete_wire", "sch_junction", "sch_items"], &["The point must lie on the wire and not at either end (not_on_wire otherwise).", "Both halves get new ids: Altium ids follow geometry."], json!({"sheet": "C:/proj/Main.SchDoc", "at": [110.49, 60.96]})),+ verb_doc("sch_delete_wire", "Delete wires or bus segments by id, by their two ends, or every wire through a point, and remove junction dots that no longer join three or more items. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "ids": "[wire id, ...]", "from": "[x, y] mm, with to: the wire with exactly these ends (either order)", "to": "[x, y] mm", "at": "[x, y] mm: every wire passing through the point", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"deleted": "[{id, from, to}]", "junctionsRemoved": "[[x, y]]", "saved": "bool"}), 120,+ "Read ids with sch_items. from/to matches one segment, not a whole route.", &["sch_items", "sch_split_wire", "sch_junction", "sch_connect_pins"], &["A polyline drawn in the editor is several wires sharing ends: from/to names one segment of it.", "An Altium wire is one polyline: deleting it removes all its segments; split it first to cut one out."], json!({"sheet": "C:/proj/Main.SchDoc", "from": [100.33, 60.96], "to": [120.65, 60.96]})),+ verb_doc("sch_edit_label", "Edit net labels: rotate, move to a point or by a delta, rename, or move every label of a net at once. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "edits": "[{id | text (with at?: [x, y] to pick one) | net (every label of the net), rotation?: 0|90|180|270, to?: [x, y] mm (one label only), by?: [dx, dy] mm, rename?: string}] (required)", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"edited": "[{id, text, at, rotation}]", "failed": "[{edit, error}]", "saved": "bool"}), 120,+ "text picks every label with that text (or the one at at); net picks every label of the net. Read ids with sch_items.", &["sch_items", "sch_connect", "sch_edit"], &["A label joins a net only where it sits on a wire or a pin end: moving it off disconnects it.", "rename changes only the labels picked: other labels with the old name stay on the old net."], json!({"sheet": "C:/proj/Main.SchDoc", "edits": [{"net": "VOUT", "by": [0, 2.54]}]})),+ verb_doc("sch_text", "Add free text to a sheet (a note, a title, a design comment) with size, angle, justification, bold and italic. Text has no electrical meaning. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "texts": "[{text, at: [x, y] mm, rotation?: 0|90|180|270, sizeMm?: 1.27, justify?: \"left bottom\", bold?: false, italic?: false}] (required)", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"added": "[{id, text, at}]", "saved": "bool"}), 120,+ "Net names are labels, not text: use sch_connect for them. Newlines in text become line breaks.", &["sch_items", "sch_edit_label"], &["Altium sizes text in points; sizeMm is converted (10 pt is about 2.54 mm). Text is one line."], json!({"sheet": "C:/proj/Main.SchDoc", "texts": [{"text": "USB input stage", "at": [50.8, 30.48], "sizeMm": 2.54, "bold": true}]})),+ verb_doc("sch_connect_pins", "Wire pins to pins on a sheet by Ref.Pin: an L-shaped route (one horizontal and one vertical leg) for each pair, with a junction dot wherever a route meets an existing wire in a T. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "pairs": "[{from: \"U1.1\", to: \"R5.2\", first?: h|v (the leg to draw first; default along the axis the from pin points), via?: [[x, y], ...] mm waypoints}] (required)", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"wired": "int", "routes": "[{from, to, points: [[x, y]], ids: [wire id]}]", "junctionsAdded": "[[x, y]]", "failed": "[{from, to, error}]", "saved": "bool"}), 120,+ "Pins are matched by number, then by name. Aligned pins get one straight wire; otherwise the route turns once. Check the result with sch_pins (connectedPins) or run_erc.", &["sch_pins", "sch_connect", "sch_delete_wire", "run_erc"], &["The route does not avoid part bodies or other wires: a leg running along another wire merges the two nets. Steer with first or via, and check with sch_pins."], json!({"sheet": "C:/proj/Main.SchDoc", "pairs": [{"from": "U1.1", "to": "R2.1"}, {"from": "U1.2", "to": "C3.1", "first": "v"}]})),+ verb_doc("sch_connect_to_bus", "Fan pins onto a bus: for each pin a wire running to the bus, a 45-degree bus entry onto it and a member label (D0, D1 ...) on the wire. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "pins": "[\"U1.1\", \"U1.2\"] Ref.Pin, in member order (required)", "bus": "id of the bus segment (default the only bus on the sheet)", "members": "[\"D0\", \"D1\"]: the member names in pin order", "prefix": "\"D\": or name members prefix + number", "start": "int, default 0: the first number with prefix", "entry": "up|down (a vertical bus) or left|right (a horizontal bus): the way the entries lean", "busLabel": "\"D[0..7]\": also label the bus", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"connected": "[{pin, member, wireId, entryId}]", "busLabel": "string or null", "failed": "[{pin, error}]", "saved": "bool"}), 120,+ "Members name the nets: members lists them in pin order, or prefix plus start counts up. Refused with entry_off_bus when an entry would miss the bus: extend the bus with sch_bus first.", &["sch_bus", "sch_bus_entry", "sch_pins"], &["Pins should face the bus; a pin facing away gets a wire across its own part.", "Two pins at the same height on a vertical bus share an entry point and collide: offset them or lean the entries differently."], json!({"sheet": "C:/proj/Main.SchDoc", "pins": ["U1.1", "U1.7"], "prefix": "D", "busLabel": "D[0..1]"})),+ verb_doc("sch_move_region", "Move everything inside a box by (dx, dy): parts, wire ends inside the box (wires crossing its edge stretch), labels, junctions, no-connect markers, texts, bus entries and sheet symbols. One undo step. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "box": "[x1, y1, x2, y2] mm (required)", "by": "[dx, dy] mm (required)", "wires": "bool, default true: move wires, buses and bus entries", "labels": "bool, default true: move labels and texts", "junctions": "bool, default true: move junctions and no-connect markers", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"moved": "{parts, wires, buses, busEntries, labels, texts, junctions, noConnects, sheets: [id]}", "saved": "bool"}), 120,+ "Parts move by their anchor point. Move by a pure dx or a pure dy to keep stretched wires straight.", &["sch_edit", "sch_items"], &["A wire with one end in the box stretches diagonally when dx and dy are both non-zero.", "Keep the move on the sheet's grid, or pins and wires stop meeting.", "A multi-part component whose parts sit on both sides of the edge splits up."], json!({"sheet": "C:/proj/Main.SchDoc", "box": [90, 40, 160, 120], "by": [25.4, 0]})),+ verb_doc("sch_fix_connectivity", "Snap near-miss wire ends onto the pin, label, sheet pin or wire end they almost touch, within a tolerance. dryRun (the default) lists the moves; dryRun:false makes them. Coordinates are mm in the sheet's frame (Altium's own, y up), the EDA Bridge Standard's schematic frame.",+ json!({"sheet": "path to the schematic sheet file (required)", "toleranceMm": "number, default 0.5", "dryRun": "bool, default TRUE", "save": "bool, default true: save the sheet after the edit"}),+ json!({"moves": "[{wireId, from, to, onto: {kind, id}, diagonal: bool}]", "unresolved": "[[x, y]]: dangling ends with nothing close", "saved": "bool"}), 120,+ "Only dangling wire ends move. Read the moves before applying them: diagonal:true means the snapped wire is no longer horizontal or vertical. Check with run_erc after.", &["sch_trace_point", "run_erc"], &["dryRun defaults to true: nothing changes until dryRun:false.", "A wide tolerance can snap onto the wrong pin: keep it under half the sheet's grid."], json!({"sheet": "C:/proj/Power.SchDoc", "toleranceMm": 0.5, "dryRun": false})), verb_doc("sch_connect", "Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). One undo step.", json!({"sheet": "path to the .SchDoc (required)", "connections": "[{designator, pin (number or name), net, kind: label|power|wire|noerc|port (default label), io?: input|output|bidirectional (port), stubMil (default 200)}] (required)", "save": "bool, default true"}), json!({"connected": "int", "results": "[{designator, pin, net, kind, result, endMil}]", "failed": "[..]", "saved": "bool"}), 90,@@ -1799,6 +1855,20 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "sheet_params" => crate::bom::sheet_params(args), "sch_place_part" => crate::sch::place_part(args), "sch_connect" => crate::sch::connect(args),+ "sch_items" => crate::schwire::items(args),+ "sch_pins" => crate::schwire::pins(args),+ "sch_trace_point" => crate::schwire::trace_point(args),+ "sch_junction" => crate::schwire::junction(args),+ "sch_bus" => crate::schwire::bus(args),+ "sch_bus_entry" => crate::schwire::bus_entry(args),+ "sch_split_wire" => crate::schwire::split_wire(args),+ "sch_delete_wire" => crate::schwire::delete_wire(args),+ "sch_edit_label" => crate::schwire::edit_label(args),+ "sch_text" => crate::schwire::text(args),+ "sch_connect_pins" => crate::schwire::connect_pins(args),+ "sch_connect_to_bus" => crate::schwire::connect_to_bus(args),+ "sch_move_region" => crate::schwire::move_region(args),+ "sch_fix_connectivity" => crate::schwire::fix_connectivity(args), "sch_edit" => crate::sch::edit(args), "annotate" => crate::sch::annotate(args), "doc_params" => crate::sch::doc_params(args),
package.json+5−1@@ -207,7 +207,11 @@ "altium jlcpcb design rules", "flip a part to the bottom side in altium", "move a component to the other side of the altium board",- "altium 3d body sizes of every part"+ "altium 3d body sizes of every part",+ "wire these pins together in altium",+ "add a bus in an altium schematic",+ "altium schematic junction dots and labels",+ "trace a net on an altium schematic sheet" ], "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+5−1@@ -199,7 +199,11 @@ "altium jlcpcb design rules", "flip a part to the bottom side in altium", "move a component to the other side of the altium board",- "altium 3d body sizes of every part"+ "altium 3d body sizes of every part",+ "wire these pins together in altium",+ "add a bus in an altium schematic",+ "altium schematic junction dots and labels",+ "trace a net on an altium schematic sheet" ], "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": {},
skills/altium-schematic-edit/SKILL.md+26−3@@ -1,9 +1,10 @@ --- name: altium-schematic-edit description: >-- Edit an Altium schematic and push it to the board: place library or Altium 365 parts, swap, wire,- annotate, hierarchical sheets, the compiled netlist, a previewed ECO, PDF. Use when asked to add a part- in altium, add a sheet, check the netlist, or update pcb.+ Edit an Altium schematic and push it to the board: place library or Altium 365 parts, swap, wire pin to pin,+ buses and bus entries, junctions, labels, text, move a region, trace a net, annotate, hierarchical sheets, the+ compiled netlist, a previewed ECO, PDF. Use when asked to add a part in altium, wire these pins, add a bus, check+ the netlist, or update pcb. --- Parent skill: **altium-bridge**@@ -55,6 +56,28 @@ when the Components panel is already open and pinned, slower when it has to be o part reached the board with its workspace footprint through `altium_update_pcb`. Altium comes to the front for both: an unpinned panel only opens, and only answers, while Altium is in front. Pass `pick` (an index or text the name contains) when the query finds several parts; an MPN finds one. +## Wiring as data, in mm (0.2.76, the EDA Bridge Standard's sch_* verbs)++The same verbs as the KiCad and Fusion bridges: millimetres in the sheet's frame (y up), pins as `Ref.Pin`. Read+first, then edit with the ids the reads give. Altium items have no stable id: an id is the item's kind plus a hash+of its geometry, valid until the item changes, and every edit answers the new ids.++| Job | Verb |+|---|---|+| Every wire, bus, entry, label, port, power port, junction, No ERC, text and sheet symbol | `altium_sch_items` |+| Every pin: outer end (where a wire must land), direction, type, what touches it, its net, the pins it reaches | `altium_sch_pins` |+| Everything connected at a point, and the whole net | `altium_sch_trace_point` |+| Wire pin to pin (an L route, junctions where it makes a T) | `altium_sch_connect_pins {pairs:[{from:"U1.1", to:"R5.2"}]}` |+| Fan pins onto a bus (wire, entry and member label each) | `altium_sch_bus` then `altium_sch_connect_to_bus {pins, prefix:"D", busLabel:"D[0..7]"}` |+| Bus entries, junction dots, free text | `altium_sch_bus_entry`, `altium_sch_junction`, `altium_sch_text` |+| Split a wire for a branch, delete wires | `altium_sch_split_wire`, `altium_sch_delete_wire` |+| Move, rotate or rename net labels (or every label of a net) | `altium_sch_edit_label` |+| Move everything in a box (wires crossing the edge stretch) | `altium_sch_move_region` |+| Snap near-miss wire ends onto their pins (plan first, dryRun defaults to true) | `altium_sch_fix_connectivity` |++Every edit takes `dryRun` (the plan, nothing changed) and saves unless `save:false`. Check the result with+`altium_sch_pins` (connectedPins) or `altium_compile`.+ ## Swap a part for another library part ```bash
src/agent/AdomAgent.pas.tmpl+297@@ -8749,6 +8749,301 @@ Begin Result := '{' + JRaw('ok','true') + ',' + JRaw('closed', IntToStr(CloseOldAgents)) + '}'; End; +{ ---------------------------------------------------------------------------------------------------------------+ Schematic wiring as data (the EDA Bridge Standard's sch_* verbs). The bridge does the planning in Rust; the agent+ only dumps a sheet's wiring and applies a list of primitive steps as one undo step.+ Every item has a KEY made of its kind and raw coordinates (and text): Altium gives wires, labels and junctions no+ stable id, so the key is the id, valid until the item changes. }++Function I2S(N : Integer) : String;+Begin+ Result := IntToStr(N);+End;++Function SchKey(Obj : ISch_GraphicalObject) : String;+Var+ J : Integer;+ S : String;+Begin+ S := '';+ If (Obj.ObjectID = eWire) Or (Obj.ObjectID = eBus) Then+ Begin+ If Obj.ObjectID = eWire Then S := 'W:' Else S := 'B:';+ For J := 1 To Obj.VerticesCount Do+ Begin+ If J > 1 Then S := S + ',';+ S := S + I2S(Obj.Vertex[J].X) + ',' + I2S(Obj.Vertex[J].Y);+ End;+ End+ Else If Obj.ObjectID = eBusEntry Then S := 'E:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ',' + I2S(Obj.Corner.X) + ',' + I2S(Obj.Corner.Y)+ Else If Obj.ObjectID = eJunction Then S := 'J:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y)+ Else If Obj.ObjectID = eNoERC Then S := 'X:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y)+ Else If Obj.ObjectID = eNetLabel Then S := 'N:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ':' + Obj.Text+ Else If Obj.ObjectID = ePort Then S := 'P:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ':' + Obj.Name+ Else If Obj.ObjectID = ePowerObject Then S := 'O:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ':' + Obj.Text+ Else If Obj.ObjectID = eLabel Then S := 'T:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ':' + Obj.Text+ Else If Obj.ObjectID = eSheetSymbol Then S := 'S:' + I2S(Obj.Location.X) + ',' + I2S(Obj.Location.Y) + ':' + Obj.SheetName.Text;+ Result := S;+End;++{ sch_dump: every wiring item of the CURRENT sheet with its key and raw coordinates, every pin of every part (outer+ end = Location moved PinLength along Orientation, as sch_connect measured), and the sheet's page. k is+ MilsToCoord(1000): the bridge turns raw units into mm with it. }+Function CmdSchDump(Lines : TStringList) : String;+Var+ Doc : ISch_Document;+ It, PIt, EIt : ISch_Iterator;+ Obj : ISch_GraphicalObject;+ C : ISch_Component;+ Pin : ISch_Pin;+ En : ISch_SheetEntry;+ S, P, V, En2 : String;+ J, Dir, HX, HY : Integer;+Begin+ Doc := SchServer.GetCurrentSchDocument;+ If (Doc = Nil) Or (Doc.ObjectID = eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_schematic') + ',' + JStr('error','no current schematic sheet (open a .SchDoc first)') + '}'; Exit; End;+ S := ''; P := '';+ It := Doc.SchIterator_Create;+ It.AddFilter_ObjectSet(MkSet(eWire, eBus, eBusEntry, eJunction, eNoERC, eNetLabel, ePort, ePowerObject, eLabel, eSheetSymbol, eSchComponent));+ { top-level items only: a part's own texts and lines come with the part (they moved with it and then could not be+ found by key, measured 2026-10-27) }+ It.SetState_IterationDepth(eIterateFirstLevel);+ Obj := It.FirstSchObject;+ While Obj <> Nil Do+ Begin+ If Obj.ObjectID = eSchComponent Then+ Begin+ C := Obj;+ PIt := C.SchIterator_Create;+ PIt.AddFilter_ObjectSet(MkSet(ePin));+ Pin := PIt.FirstSchObject;+ While Pin <> Nil Do+ Begin+ If ((Pin.OwnerPartId = C.CurrentPartID) Or (Pin.OwnerPartId = 0)) And (Pin.OwnerPartDisplayMode = C.DisplayMode) Then+ Begin+ Dir := Pin.Orientation;+ HX := Pin.Location.X; HY := Pin.Location.Y;+ If Dir = 0 Then HX := HX + Pin.PinLength+ Else If Dir = 1 Then HY := HY + Pin.PinLength+ Else If Dir = 2 Then HX := HX - Pin.PinLength+ Else HY := HY - Pin.PinLength;+ If P <> '' Then P := P + ',';+ P := P + '["' + JsonEsc(C.Designator.Text) + '","' + JsonEsc(Pin.Designator) + '","' + JsonEsc(Pin.Name) + '",' ++ I2S(Pin.Electrical) + ',' + I2S(HX) + ',' + I2S(HY) + ',' + I2S(Dir) + ',' + JBool(Pin.IsHidden) + ',' ++ I2S(Pin.Location.X) + ',' + I2S(Pin.Location.Y) + ']';+ End;+ Pin := PIt.NextSchObject;+ End;+ C.SchIterator_Destroy(PIt);+ If S <> '' Then S := S + ',';+ S := S + '{"t":"C","key":"","ref":"' + JsonEsc(C.Designator.Text) + '","x":' + I2S(C.Location.X) + ',"y":' + I2S(C.Location.Y) ++ ',"lib":"' + JsonEsc(C.LibReference) + '","part":' + I2S(C.CurrentPartID) + ',"rot":' + I2S(C.Orientation) + ',"mirror":' + JBool(C.IsMirrored) + '}';+ End+ Else+ Begin+ V := '';+ If (Obj.ObjectID = eWire) Or (Obj.ObjectID = eBus) Then+ Begin+ For J := 1 To Obj.VerticesCount Do+ Begin+ If J > 1 Then V := V + ',';+ V := V + '[' + I2S(Obj.Vertex[J].X) + ',' + I2S(Obj.Vertex[J].Y) + ']';+ End;+ V := '"pts":[' + V + ']';+ End+ Else+ Begin+ V := '"x":' + I2S(Obj.Location.X) + ',"y":' + I2S(Obj.Location.Y);+ If Obj.ObjectID = eBusEntry Then V := V + ',"cx":' + I2S(Obj.Corner.X) + ',"cy":' + I2S(Obj.Corner.Y)+ Else If (Obj.ObjectID = eNetLabel) Or (Obj.ObjectID = eLabel) Then V := V + ',"text":"' + JsonEsc(Obj.Text) + '","rot":' + I2S(Obj.Orientation) + ',"just":' + I2S(Obj.Justification)+ Else If Obj.ObjectID = ePowerObject Then V := V + ',"text":"' + JsonEsc(Obj.Text) + '","rot":' + I2S(Obj.Orientation) + ',"style":' + I2S(Obj.Style)+ Else If Obj.ObjectID = ePort Then V := V + ',"text":"' + JsonEsc(Obj.Name) + '","w":' + I2S(Obj.Width) + ',"style":' + I2S(Obj.Style) + ',"io":' + I2S(Obj.IOType)+ Else If Obj.ObjectID = eSheetSymbol Then+ Begin+ En2 := '';+ EIt := Obj.SchIterator_Create;+ EIt.AddFilter_ObjectSet(MkSet(eSheetEntry));+ En := EIt.FirstSchObject;+ While En <> Nil Do+ Begin+ If En2 <> '' Then En2 := En2 + ',';+ En2 := En2 + '["' + JsonEsc(En.Name) + '",' + I2S(En.Side) + ',' + I2S(En.DistanceFromTop) + ',' + I2S(En.IOType) + ']';+ En := EIt.NextSchObject;+ End;+ Obj.SchIterator_Destroy(EIt);+ V := V + ',"text":"' + JsonEsc(Obj.SheetName.Text) + '","file":"' + JsonEsc(Obj.SheetFileName.Text) + '","w":' + I2S(Obj.XSize) + ',"h":' + I2S(Obj.YSize) + ',"entries":[' + En2 + ']';+ End;+ End;+ If S <> '' Then S := S + ',';+ S := S + '{"t":"' + Copy(SchKey(Obj), 1, 1) + '","key":"' + JsonEsc(SchKey(Obj)) + '",' + V + '}';+ End;+ Obj := It.NextSchObject;+ End;+ Doc.SchIterator_Destroy(It);+ Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('k', I2S(MilsToCoord(1000))) + ',' ++ JRaw('page', '{"style":' + I2S(Doc.SheetStyle) + ',"custom":' + JBool(Doc.UseCustomSheet) + ',"cx":' + I2S(Doc.CustomX) + ',"cy":' + I2S(Doc.CustomY) + '}') + ',' ++ JRaw('items', '[' + S + ']') + ',' + JRaw('pins', '[' + P + ']') + '}';+End;++Function SchFindByKey(Doc : ISch_Document; Key : String) : ISch_GraphicalObject;+Var+ It : ISch_Iterator;+ Obj : ISch_GraphicalObject;+Begin+ Result := Nil;+ It := Doc.SchIterator_Create;+ It.AddFilter_ObjectSet(MkSet(eWire, eBus, eBusEntry, eJunction, eNoERC, eNetLabel, ePort, ePowerObject, eLabel, eSheetSymbol));+ It.SetState_IterationDepth(eIterateFirstLevel);+ Obj := It.FirstSchObject;+ While Obj <> Nil Do+ Begin+ If SchKey(Obj) = Key Then Begin Result := Obj; Break; End;+ Obj := It.NextSchObject;+ End;+ Doc.SchIterator_Destroy(It);+End;++Procedure SchRegister(Doc : ISch_Document; Obj : ISch_GraphicalObject);+Begin+ Doc.RegisterSchObjectInContainer(Obj);+ SchServer.RobotManager.SendMessage(Doc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, Obj.I_ObjectAddress);+End;++{ points "x,y,x,y,..." (raw) onto a new or existing wire/bus }+Procedure SchSetVertices(Obj : ISch_GraphicalObject; Pts : String);+Var+ L : TStringList;+ J, N : Integer;+Begin+ L := TStringList.Create; L.Delimiter := ','; L.StrictDelimiter := True; L.DelimitedText := Pts;+ N := L.Count Div 2;+ Obj.Location := Point(AdomInt(L[0]), AdomInt(L[1]));+ Obj.VerticesCount := N;+ For J := 1 To N Do Obj.Vertex[J] := Point(AdomInt(L[2 * J - 2]), AdomInt(L[2 * J - 1]));+ L.Free;+End;++{ sch_ops: primitive steps, one undo step. Fields after the kind letter, | separated, raw coordinates:+ W|pts a new wire through the points "x,y,x,y,..." B|pts a new bus+ E|x|y|cx|cy a bus entry from (x,y) to the corner (cx,cy) J|x|y a junction X|x|y a No ERC marker+ N|text|x|y|rot|just a net label T|text|x|y|rot|pt|bold|italic|just free text+ D|key delete the item with that key V|key|pts give a wire/bus new points+ G|key|dx|dy move an item by dx, dy L|key|text|x|y|rot edit a net label+ C|ref|dx|dy move a part by dx, dy+ Each step answers ok, or why not, and the key it made or touched. }+Function CmdSchOps(Lines : TStringList; Payload : String) : String;+Var+ Doc : ISch_Document;+ Ops : TStringList;+ CL : TInterfaceList;+ Obj : ISch_GraphicalObject;+ C : ISch_Component;+ Op, K, Res, NewKey, S : String;+ I, J, NOk : Integer;+Begin+ Doc := SchServer.GetCurrentSchDocument;+ If (Doc = Nil) Or (Doc.ObjectID = eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_schematic') + ',' + JStr('error','no current schematic sheet (open a .SchDoc first)') + '}'; Exit; End;+ Ops := TStringList.Create; Ops.Text := Payload;+ S := ''; NOk := 0;+ SchServer.ProcessControl.PreProcess(Doc, '');+ For I := 0 To Ops.Count - 1 Do+ Begin+ Op := Ops[I];+ If Trim(Op) = '' Then Continue;+ K := FieldP(Op, 1); Res := 'ok'; NewKey := ''; gInputError := '';+ If (K = 'W') Or (K = 'B') Then+ Begin+ If K = 'W' Then Obj := SchServer.SchObjectFactory(eWire, eCreate_Default) Else Obj := SchServer.SchObjectFactory(eBus, eCreate_Default);+ SchSetVertices(Obj, FieldP(Op, 2));+ Obj.LineWidth := eSmall;+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If K = 'E' Then+ Begin+ Obj := SchServer.SchObjectFactory(eBusEntry, eCreate_Default);+ Obj.Location := Point(AdomInt(FieldP(Op, 2)), AdomInt(FieldP(Op, 3)));+ Obj.Corner := Point(AdomInt(FieldP(Op, 4)), AdomInt(FieldP(Op, 5)));+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If (K = 'J') Or (K = 'X') Then+ Begin+ If K = 'J' Then Obj := SchServer.SchObjectFactory(eJunction, eCreate_Default) Else Obj := SchServer.SchObjectFactory(eNoERC, eCreate_Default);+ Obj.Location := Point(AdomInt(FieldP(Op, 2)), AdomInt(FieldP(Op, 3)));+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If K = 'N' Then+ Begin+ Obj := SchServer.SchObjectFactory(eNetLabel, eCreate_Default);+ Obj.Text := FieldP(Op, 2);+ Obj.Location := Point(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4)));+ Obj.Orientation := AdomInt(FieldP(Op, 5));+ If FieldP(Op, 6) <> '' Then Obj.Justification := AdomInt(FieldP(Op, 6));+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If K = 'T' Then+ Begin+ Obj := SchServer.SchObjectFactory(eLabel, eCreate_Default);+ Obj.Text := FieldP(Op, 2);+ Obj.Location := Point(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4)));+ Obj.Orientation := AdomInt(FieldP(Op, 5));+ If AdomInt(FieldP(Op, 6)) > 0 Then+ Obj.FontId := SchServer.FontManager.GetFontID(AdomInt(FieldP(Op, 6)), 0, False, FieldP(Op, 8) = '1', FieldP(Op, 7) = '1', False, 'Times New Roman');+ If FieldP(Op, 9) <> '' Then Obj.Justification := AdomInt(FieldP(Op, 9));+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If K = 'C' Then+ Begin+ CL := SheetCompsOf(Doc, FieldP(Op, 2));+ If CL.Count = 0 Then Res := 'designator not on this sheet';+ For J := 0 To CL.Count - 1 Do+ Begin+ C := CL[J];+ SchServer.RobotManager.SendMessage(C.I_ObjectAddress, c_BroadCast, SCHM_BeginModify, c_NoEventData);+ C.MoveByXY(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4)));+ SchServer.RobotManager.SendMessage(C.I_ObjectAddress, c_BroadCast, SCHM_EndModify, c_NoEventData);+ C.GraphicallyInvalidate;+ End;+ CL.Free;+ NewKey := FieldP(Op, 2);+ End+ Else If (K = 'D') Or (K = 'V') Or (K = 'G') Or (K = 'L') Then+ Begin+ Obj := SchFindByKey(Doc, FieldP(Op, 2));+ If Obj = Nil Then Res := 'not found: the item changed since it was read'+ Else If K = 'D' Then+ Begin+ Doc.RemoveSchObject(Obj);+ SchServer.RobotManager.SendMessage(Doc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, Obj.I_ObjectAddress);+ End+ Else+ Begin+ SchServer.RobotManager.SendMessage(Obj.I_ObjectAddress, c_BroadCast, SCHM_BeginModify, c_NoEventData);+ If K = 'V' Then SchSetVertices(Obj, FieldP(Op, 3))+ Else If K = 'G' Then Obj.MoveByXY(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4)))+ Else+ Begin+ If FieldP(Op, 3) <> '' Then Obj.Text := FieldP(Op, 3);+ If FieldP(Op, 4) <> '' Then Obj.Location := Point(AdomInt(FieldP(Op, 4)), AdomInt(FieldP(Op, 5)));+ If FieldP(Op, 6) <> '' Then Obj.Orientation := AdomInt(FieldP(Op, 6));+ End;+ SchServer.RobotManager.SendMessage(Obj.I_ObjectAddress, c_BroadCast, SCHM_EndModify, c_NoEventData);+ Obj.GraphicallyInvalidate;+ NewKey := SchKey(Obj);+ End;+ End+ Else Res := 'unknown step ' + K;+ If gInputError <> '' Then Res := 'bad number ' + gInputError;+ If Res = 'ok' Then NOk := NOk + 1;+ If S <> '' Then S := S + ',';+ S := S + '{' + JStr('result', Res) + ',' + JStr('key', NewKey) + '}';+ End;+ SchServer.ProcessControl.PostProcess(Doc, '');+ Doc.GraphicallyInvalidate;+ Ops.Free;+ Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('applied', I2S(NOk)) + ',' + JRaw('results', '[' + S + ']') + '}';+End;++ Function Dispatch(Cmd : String; Lines : TStringList; Payload : String) : String; Begin If Cmd = 'ping' Then Result := CmdPing(Lines)@@ -8794,6 +9089,8 @@ Begin Else If Cmd = 'schematic_data' Then Result := CmdSchematicData(Lines) Else If Cmd = 'sheet_params' Then Result := CmdSheetParams(Lines) Else If Cmd = 'sch_connect' Then Result := CmdSchConnect(Lines, Payload)+ Else If Cmd = 'sch_dump' Then Result := CmdSchDump(Lines)+ Else If Cmd = 'sch_ops' Then Result := CmdSchOps(Lines, Payload) Else If Cmd = 'sheet_symbol' Then Result := CmdSheetSymbol(Lines, Payload) Else If Cmd = 'sheet_ports' Then Result := CmdSheetPorts(Lines, Payload) Else If Cmd = 'teardrop_count' Then Result := CmdTeardropCount(Lines)
src/bridge.json+29−1@@ -172,11 +172,25 @@ "altium_run_outjob", "altium_run_script", "altium_save",+ "altium_sch_bus",+ "altium_sch_bus_entry", "altium_sch_connect",+ "altium_sch_connect_pins",+ "altium_sch_connect_to_bus",+ "altium_sch_delete_wire", "altium_sch_edit",+ "altium_sch_edit_label",+ "altium_sch_fix_connectivity",+ "altium_sch_items",+ "altium_sch_junction",+ "altium_sch_move_region",+ "altium_sch_pins", "altium_sch_place_part", "altium_sch_sheet_symbol",+ "altium_sch_split_wire", "altium_sch_swap_part",+ "altium_sch_text",+ "altium_sch_trace_point", "altium_sch_zoom", "altium_schematic_data", "altium_schematic_review",@@ -377,7 +391,21 @@ "outjob_info": 30, "find_symbol": 300, "part_parameters": 300,- "bodies": 180+ "bodies": 180,+ "sch_items": 150,+ "sch_pins": 150,+ "sch_trace_point": 150,+ "sch_junction": 150,+ "sch_bus": 150,+ "sch_bus_entry": 150,+ "sch_split_wire": 150,+ "sch_delete_wire": 150,+ "sch_edit_label": 150,+ "sch_text": 150,+ "sch_connect_pins": 150,+ "sch_connect_to_bus": 150,+ "sch_move_region": 150,+ "sch_fix_connectivity": 150 }, "prefixes": [ {