by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
main
Colby Knox
0.2.77 source: the EDA Bridge Standard's project, library-part and render verbs (13 new, 245 in all), engine 0.1.4, sav…
126a893
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
//! One shareable page per board: every check the bridge has, run against the live board and its project, with a
//! picture of the board, written as a single self-contained HTML file beside the project.
use serde_json::{json, Value};
fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) }
fn txt(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
Value::Null => String::new(),
// lists read as plain text, not JSON
Value::Array(a) => a.iter().map(txt).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(", "),
other => other.to_string(),
}
}
/// One section of the page: a title, a verdict (true, false, None = information) and rows of (label, value). Pure.
pub struct Section { pub title: String, pub ok: Option<bool>, pub summary: String, pub rows: Vec<(String, String)> }
/// The sections from the checks' replies (any may be an error reply: it shows as such). Pure.
pub fn sections(c: &Value) -> Vec<Section> {
let mut out = Vec::new();
let failed = |r: &Value| r.get("success").and_then(|b| b.as_bool()) == Some(false);
let err = |title: &str, r: &Value| Section { title: title.into(), ok: None, summary: format!("not run: {}", txt(r.get("error").unwrap_or(&Value::Null))), rows: vec![] };
// design rules
let d = &c["drc"];
out.push(if failed(d) { err("Design rules (Altium DRC)", d) } else {
Section { title: "Design rules (Altium DRC)".into(), ok: Some(d["errors"].as_i64() == Some(0) && d["unconnected"].as_i64() == Some(0)),
summary: format!("{} violations, {} unconnected", txt(&d["errors"]), txt(&d["unconnected"])),
rows: d["violations"].as_array().cloned().unwrap_or_default().iter().take(30).map(|v| (txt(&v["rule"]), txt(&v["objects"]))).collect() } });
let f = &c["fab"];
out.push(if failed(f) { err("JLCPCB fab limits", f) } else {
let mut rows: Vec<(String, String)> = f["outsideLimits"].as_array().cloned().unwrap_or_default().iter().map(|o| (txt(&o["limit"]), format!("board {} mm, limit {} mm", txt(&o["boardMm"]), txt(&o["limitMm"])))).collect();
for k in ["track", "viaDrill", "padHole", "edgeClearance", "silkText", "boardSize"] { if let Some(m) = f["measured"].get(k) { rows.push((format!("measured {k}"), format!("{} mm", txt(&m["mm"])))); } }
Section { title: "JLCPCB fab limits".into(), ok: f["fits"].as_bool(), summary: format!("{} outside JLCPCB's limits", f["outsideLimits"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });
let a = &c["assembly"];
out.push(if failed(a) { err("JLCPCB assembly", a) } else {
let rows = ["economic", "standard"].iter().flat_map(|t| a[*t]["rules"].as_array().cloned().unwrap_or_default().into_iter().filter(|r| r["ok"] == json!(false)).map(move |r| (format!("{t}: {}", txt(&r["rule"])), txt(&r["detail"])))).collect();
Section { title: "JLCPCB assembly".into(), ok: Some(!a["service"].is_null()), summary: format!("tier: {}", if a["service"].is_null() { "none passes yet".to_string() } else { txt(&a["service"]) }), rows } });
let s = &c["schematic"];
out.push(if failed(s) { err("Schematic review", s) } else {
let rows = s["errors"].as_array().cloned().unwrap_or_default().iter().chain(s["warnings"].as_array().cloned().unwrap_or_default().iter()).take(30)
.map(|w| (txt(&w["check"]), [w.get("pin"), w.get("net"), w.get("ics")].iter().flatten().map(|v| txt(v)).collect::<Vec<_>>().join(" "))).collect();
Section { title: "Schematic review".into(), ok: s["ok"].as_bool(), summary: format!("{} errors, {} warnings, {} pins on {} nets", s["errors"].as_array().map(|a| a.len()).unwrap_or(0), s["warnings"].as_array().map(|a| a.len()).unwrap_or(0), txt(&s["pins"]), txt(&s["nets"])), rows } });
let p = &c["pinPad"];
out.push(if failed(p) { err("Symbols against footprints", p) } else {
Section { title: "Symbols against footprints".into(), ok: p["ok"].as_bool(), summary: format!("{} of {} parts match", txt(&p["matching"]), txt(&p["partsChecked"])),
rows: p["mismatches"].as_array().cloned().unwrap_or_default().iter().map(|m| (txt(&m["ref"]), format!("pins without pad {} / pads without pin {}", txt(&m["pinsWithoutPad"]), txt(&m["padsWithoutPin"])))).collect() } });
let i = &c["impedance"];
out.push(if failed(i) { err("Controlled impedance", i) } else {
Section { title: "Controlled impedance (50 ohm, 90 ohm pairs)".into(), ok: None, summary: "track widths from the stack-up".into(),
rows: i["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}: 50 ohm {} mm; 90 ohm pair {} / {} mm", txt(&l["model"]), txt(&l["width"]), txt(&l["diffWidth"]), txt(&l["diffGap"])))).collect() } });
let r = &c["returnPath"];
out.push(if failed(r) { err("Return paths", r) } else {
Section { title: "Return paths".into(), ok: r["ok"].as_bool(), summary: format!("{} net-layer runs over a gap in the reference copper", r["nets"].as_array().map(|a| a.len()).unwrap_or(0)),
rows: r["nets"].as_array().cloned().unwrap_or_default().iter().take(20).map(|n| (format!("{} on {}", txt(&n["net"]), txt(&n["layer"])), format!("{} mm of {} mm ({}%)", txt(&n["unreferencedMm"]), txt(&n["lengthMm"]), txt(&n["percent"])))).collect() } });
let b = &c["balance"];
out.push(if failed(b) { err("Copper balance", b) } else {
Section { title: "Copper balance".into(), ok: b["balanced"].as_bool(), summary: "copper share per layer; mirrored pairs within 20 points".into(),
rows: b["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}% ({} mm2)", txt(&l["percent"]), txt(&l["copperMm2"])))).collect() } });
let h = &c["heights"];
out.push(if failed(h) { err("3D heights and clearance", h) } else {
let mut rows: Vec<(String, String)> = h["heights"].as_array().cloned().unwrap_or_default().iter().take(8).map(|x| (txt(&x["ref"]), format!("{} mm, {}", txt(&x["heightMm"]), txt(&x["side"])))).collect();
for col in h["collisions"].as_array().cloned().unwrap_or_default() { rows.push(("collision".into(), format!("{} by {} mm", txt(&col["parts"]), txt(&col["overlapMm"])))); }
Section { title: "3D heights and clearance".into(), ok: Some(h["collisions"].as_array().map(|a| a.is_empty()).unwrap_or(true)), summary: format!("{} bodies; {} parts without a 3D body", txt(&h["bodies"]), h["noBody"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });
out
}
/// The page. Dark by default with a light scheme, tokens on :root. Pure.
pub fn page(board: &str, when: &str, version: &str, shot: Option<&str>, secs: &[Section]) -> String {
let badge = |ok: Option<bool>| match ok { Some(true) => "<span class=\"b ok\">pass</span>", Some(false) => "<span class=\"b no\">needs work</span>", None => "<span class=\"b info\">info</span>" };
let mut body = String::new();
for s in secs {
body.push_str(&format!("<section><h2>{} {}</h2><p class=\"sum\">{}</p>", esc(&s.title), badge(s.ok), esc(&s.summary)));
if !s.rows.is_empty() {
body.push_str("<table>");
for (k, v) in &s.rows { body.push_str(&format!("<tr><th>{}</th><td>{}</td></tr>", esc(k), esc(v))); }
body.push_str("</table>");
}
body.push_str("</section>");
}
let pass = secs.iter().filter(|s| s.ok == Some(true)).count();
let work = secs.iter().filter(|s| s.ok == Some(false)).count();
let img = shot.map(|b| format!("<img alt=\"the board in Altium\" src=\"data:image/png;base64,{b}\">")).unwrap_or_default();
format!(r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="dark"><title>Board report</title><style>
:root{{--bg:#101418;--panel:#182028;--ink:#e6edf3;--dim:#9aa7b4;--line:#2a3542;--ok:#3fb950;--no:#f0883e;--info:#58a6ff}}
body{{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}}
main{{max-width:960px;margin:0 auto;padding:24px 16px}} h1{{font-size:24px;margin:0 0 4px}} .meta{{color:var(--dim);margin:0 0 16px}}
img{{width:100%;border:1px solid var(--line);border-radius:8px;margin:8px 0 16px}}
section{{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:12px 16px;margin:12px 0}}
h2{{font-size:17px;margin:0;display:flex;gap:8px;align-items:center}} .sum{{color:var(--dim);margin:4px 0 8px}}
.b{{font-size:12px;border-radius:999px;padding:1px 8px;border:1px solid}} .ok{{color:var(--ok)}} .no{{color:var(--no)}} .info{{color:var(--info)}}
table{{width:100%;border-collapse:collapse;font-size:13px}} th,td{{text-align:left;padding:4px 6px;border-top:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}} th{{width:34%;color:var(--dim);font-weight:500}}
</style></head><body><main><h1>{}</h1><p class="meta">{} · {} pass, {} need work · altium-bridge {}</p>{}{}</main></body></html>"#,
esc(board), esc(when), pass, work, esc(version), img, body)
}
/// "YYYY-MM-DDTHH:MM:SSZ" for seconds since 1970 (civil-from-days, no date crate). Pure.
pub fn iso_utc(secs: i64) -> String {
let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));
let z = days + 719468;
let era = z.div_euclid(146097);
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, (rem % 3600) / 60, rem % 60)
}
/// "YYYY-MM-DD HH:MM UTC" now (civil-from-days, no date crate). Pure but for the clock.
fn utc_now() -> String {
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));
let z = days + 719468;
let era = z.div_euclid(146097);
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
format!("{y:04}-{m:02}-{d:02} {:02}:{:02} UTC", rem / 3600, (rem % 3600) / 60)
}
/// altium_board_report {projectPath, pcbPath, out?}
pub fn board_report(args: &Value) -> Value {
use crate::support::s;
if let Some(g) = crate::support::need_licensed() { return g; }
let (Some(prj), Some(pcb)) = (s(args, "projectPath"), s(args, "pcbPath")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) and pcbPath (.PcbDoc) are required"});
};
let t0 = std::time::Instant::now();
let mut c = json!({});
c["schematic"] = crate::schreview::schematic_review(&json!({"projectPath": prj}));
c["pinPad"] = crate::schreview::pin_pad_check(&json!({"projectPath": prj, "pcbPath": pcb}));
c["fab"] = crate::fab::fab_check(&json!({"filePath": pcb, "fab": "jlcpcb"}));
c["assembly"] = crate::assembly::assembly_check(&json!({"filePath": pcb, "projectPath": prj}));
c["impedance"] = crate::impedance::impedance(&json!({"filePath": pcb, "z0": 50, "diff": 90}));
c["returnPath"] = crate::coppermap::return_path(&json!({"filePath": pcb}));
c["balance"] = crate::coppermap::copper_balance(&json!({"filePath": pcb}));
c["heights"] = crate::bodies::height_check(&json!({"filePath": pcb}));
c["drc"] = crate::routing::routing_drc(&json!({"full": true}));
// the picture: the board framed in Altium's own window (no focus taken)
let st = crate::routing::routing_state(&json!({}));
let mut shot = None;
if let Some((x0, y0, x1, y1)) = crate::fab::outline_bbox(&st) {
let m = ((x1 - x0).max(y1 - y0)) * 0.05;
crate::routing::zoom_to(&json!({"rect": [x0 - m, y0 - m, x1 + m, y1 + m]}));
if let Some(h) = crate::instance::main_window().and_then(|w| w["hwnd"].as_i64()) {
let r = crate::ab::call("desktop_screenshot_base64", json!({"hwnd": h}), &[], 20);
shot = r.get("image").or_else(|| r.get("base64")).and_then(|i| i.as_str()).map(String::from);
}
}
let secs = sections(&c);
let name = std::path::Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());
let out = s(args, "out").unwrap_or_else(|| std::path::Path::new(&prj).parent().unwrap_or(std::path::Path::new(".")).join(format!("{name} report.html")).to_string_lossy().to_string());
let when = utc_now();
let html = page(&name, &when, crate::BRIDGE_VERSION, shot.as_deref(), &secs);
if let Err(e) = std::fs::write(&out, html) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{out}: {e}")}); }
json!({"success": true, "report": out, "sections": secs.iter().map(|s| json!({"title": s.title, "ok": s.ok, "summary": s.summary})).collect::<Vec<_>>(),
"pass": secs.iter().filter(|s| s.ok == Some(true)).count(), "needsWork": secs.iter().filter(|s| s.ok == Some(false)).count(), "picture": shot.is_some(), "elapsedSec": (t0.elapsed().as_secs_f64() * 10.0).round() / 10.0,
"_hint": "report is a single HTML file (the board's picture embedded): open it in a browser or send it. Each section's verdict and rows come from the verb named in it: run that verb for the full reply."})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso_dates() {
assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");
assert_eq!(iso_utc(1793134800), "2026-10-27T21:00:00Z");
}
#[test]
fn sections_read_every_check_and_the_page_escapes() {
let c = json!({"drc": {"success": true, "errors": 0, "unconnected": 0, "violations": []},
"fab": {"success": true, "fits": false, "outsideLimits": [{"limit": "minTrack", "boardMm": 0.08, "limitMm": 0.1}], "measured": {"track": {"mm": 0.08}}},
"assembly": {"success": false, "error": "no project"},
"schematic": {"success": true, "ok": true, "errors": [], "warnings": [{"check": "single_pin_net", "net": "<X>"}], "pins": 10, "nets": 4}});
let s = sections(&c);
assert_eq!(s[0].ok, Some(true));
assert_eq!(s[1].ok, Some(false));
assert!(s[2].summary.starts_with("not run"));
let html = page("lane", "2026-10-26", "0.2.75", None, &s);
assert!(html.contains("<X>") && !html.contains("<X>"));
assert!(html.contains("color-scheme\" content=\"dark"));
assert_eq!(txt(&json!(["Pad U2-5", "Pad U3-4"])), "Pad U2-5, Pad U3-4");
}
}