← Commit history
Publish 0.3.0
13 files changed
+2151
CHANGELOG.mdadded+17@@ -0,0 +1,17 @@+# Changelog++## 0.3.0 — 2026-09-25+- Crystal load capacitors upgraded to a full Pierce oscillator CL calculator: caps for a rated CL or CL from C1/C2+ (asymmetric), gm_crit and gain margin ≥ 5, drive level from a measured Vpp, frequency pulling and trim sensitivity.+ Verified against ST AN2867 Rev 10 §3.3–3.5 (tests reproduce its worked examples).+- Live schematics and PCB cross-sections for 26 calculators (`schematics.js`), labelled with the entered values; also as+ SVG via `GET /api/schematic` and `hwcalc calc … --svg`. Setting `show_schematics`.+- SOURCES.md standards register; `hwcalc-calculator-standards` dev skill and `hwcalc-release` publish skill.++## 0.2.0 — 2026-09-25+- 20 → 40 calculators after a market review. IPC-2152 curve fit is the trace-width default (IPC-2221 kept as legacy);+ IPC-2221C Table 6-1 spacing; IPC-2141 differential pairs; vias; fusing; attenuators; VSWR; regulators; MOSFET loss; PDN;+ op-amp; 555; NTC; spiral inductor.++## 0.1.0 — 2026-09-25+- First version: 20 calculators, Hydrogen UI, CLI, HTTP API.
SOURCES.mdadded+67@@ -0,0 +1,67 @@+# Hardware Calculator — sources register++Generated by `node scripts/sources.js` for v0.3.0. Do not edit the calculator table by hand;+edit `ref` / `formula` in calcs.js and regenerate. The standards register above it is maintained by hand in+`docs/standards.md`.++## Standards register++Every row was checked against the publisher or two independent reproductions on the date shown. Re-check a row+before relying on it for a change, and update the date when you do.++| Standard / source | Current revision | Checked | How hwcalc uses it |+|---|---|---|---|+| IPC-2221 Generic Standard on Printed Board Design | Rev C, Dec 2023 (supersedes B, 2012) | 2026-09-25 | Table 6-1 conductor spacing B1/B2/B4 (sea-level values unchanged from B, cross-checked against two reproductions); legacy trace-width formula k = 0.048 / 0.024. B5 and A5–A7 not modelled. |+| IPC-2152 Current-Carrying Capacity | Rev 0, 2009 (still current; chart-only) | 2026-09-25 | Default trace width: published baseline-chart curve fit (smps.us). Modifiers (board thickness, planes) not modelled: conservative. |+| IPC-2141A Controlled Impedance Design | 2004 | 2026-09-25 | Microstrip / stripline and edge-coupled differential closed forms (±5–10 %; confirm with a field solver). |+| IEC 60063 preferred number series | E3–E192 | 2026-09-25 | E-series values, including the E192 920 exception; full E96 table under test. |+| IEC 60062 marking codes | — | 2026-09-25 | Resistor colour bands; EIA-96 SMD codes. |+| NXP UM10204 I²C-bus specification | Rev 7.0, 1 Oct 2021 (title of nxp.com/docs/en/user-guide/UM10204.pdf) | 2026-09-25 | Pull-up min/max from VOL/IOL and rise time. |+| ST AN2867 Oscillator design guide | Rev 10, Aug 2015 | 2026-09-25 | Crystal CL, gm_crit, gain margin ≥ 5, drive level (§3.3–3.5). Read from a vendor-hosted mirror PDF (st.com is unreachable from Adom containers). |+| Onderdonk fusing equation | classical | 2026-09-25 | Fusing current for traces and wires. |+| Mohan, Hershenson, Boyd & Lee, IEEE JSSC 34(10), 1999 | — | 2026-09-25 | Planar spiral inductance (modified Wheeler). |++## Calculators (40)++| id | Calculator | Drawing | Formula | Reference |+|---|---|---|---|---|+| `ohms` | Ohm's law & power | — | `V = I·R, P = V·I = I²R = V²/R` | Ohm / Joule |+| `divider` | Voltage divider | yes | `Vout = Vin · (R2‖RL) / (R1 + R2‖RL), Rout = R1‖R2` | Kirchhoff |+| `led` | LED series resistor | yes | `R = (Vs − n·Vf) / If` | Ohm; use the datasheet Vf at the chosen If |+| `filter` | RC / RL / LC time constants & cut-off | yes | `RC: fc = 1/(2πRC), τ = RC · RL: fc = R/(2πL), τ = L/R · LC: f0 = 1/(2π√(LC)), Z0 = √(L/C)` | First-order / second-order networks |+| `trace` | Trace width for current (IPC-2152 / IPC-2221) | yes | `IPC-2152 baseline: A = (117.555·ΔT^−0.913 + 1.15)·I^(0.84·ΔT^−0.108 + 1.159) · IPC-2221: I = k·ΔT^0.44·A^0.725 (k 0.048 ext / 0.024 int) · A in mil²; R = ρ(T)·L/(w·t)` | IPC-2152 (2009, current revision) baseline chart via the published curve fit on smps.us; IPC-2221C (2023) §6.2 retains the IPC-2221 chart fit. ρCu = 1.724e-8 Ω·m, α = 0.00393/°C |+| `impedance` | Microstrip / stripline impedance (IPC-2141) | yes | `Microstrip: Z0 = 87/√(εr+1.41)·ln(5.98h/(0.8w+t)) · Stripline: Z0 = 60/√εr·ln(1.9b/(0.8w+t))` | IPC-2141 closed forms (±5–10 %; use a field solver for final stack-ups) |+| `ldo` | Linear regulator dissipation | yes | `Pd = (Vin − Vout)·Iout + Vin·Iq, Tj = Ta + Pd·θJA` | Standard LDO thermal model (θJA is layout-dependent) |+| `buck` | Buck converter: inductor & ripple | yes | `D = Vout/(Vin·η), L = Vout·(Vin−Vout)/(ΔIL·fsw·Vin), ΔVout = ΔIL/(8·fsw·Cout) + ΔIL·ESR` | TI SLVA477B (basic buck power stage) |+| `boost` | Boost converter: inductor & ripple | yes | `D = 1 − Vin·η/Vout, L = Vin·(Vout−Vin)/(ΔIL·fsw·Vout), ΔVout = Iout·D/(fsw·Cout) + ESR·Ipk` | TI SLVA372C (basic boost power stage) |+| `holdup` | Hold-up / bulk capacitor | yes | `Constant P: t = C·(V1² − V2²)/(2P) · Constant I: t = C·(V1 − V2)/I` | Capacitor energy E = ½CV² |+| `battery` | Battery life (duty-cycled load) | — | `Iavg = Ia·d + Is·(1−d), life = C·derate / Iavg` | Charge balance (ignores self-discharge and temperature) |+| `i2c` | I²C pull-up resistor range | yes | `Rmin = (VDD − VOL)/IOL, Rmax = tr / (0.8473·Cb)` | NXP UM10204 §7.1 (tr max 1000/300/120 ns; IOL 3/3/20 mA; VOL 0.4 V, or 0.2·VDD below 2 V) |+| `crystal` | Crystal oscillator load capacitors (CL) | yes | `CL = C1·C2/(C1+C2) + Cs → C1 = C2 = 2·(CL − Cs)<br>gm_crit = 4·ESR·(2πF)²·(C0 + CL)², gain margin = gm/gm_crit ≥ 5<br>pulling Δf/f = Cm/(2(C0+CL)), trim sensitivity = −Cm/(2(C0+CL)²)<br>DL = ESR·IQ², IQ = 2πF·(Vpp/2√2)·(C1 + Cs/2 + Cprobe)` | ST AN2867 Rev 10 §3.3–3.5 (CL, gm_crit, gain margin ≥ 5, drive level); pulling / trim sensitivity from the crystal equivalent circuit (CTS, ECS crystal notes) |+| `shunt` | Current-sense shunt | yes | `Vsense = I·R, P = I²R, Vout = G·I·R, LSB current = Vref/(2^N·G·R)` | Ohm / Joule |+| `adc` | ADC resolution & ideal SNR | — | `LSB = Vref/2^N, code = ⌊Vin/LSB⌋, SNR = 6.02N + 1.76 dB, q-noise = LSB/√12` | Ideal quantiser |+| `thermal` | Junction temperature & heatsink | yes | `Tj = Ta + P·(θJC + θCS + θSA)` | Series thermal resistance model |+| `wire` | Wire gauge: resistance & drop | — | `d = 0.127 mm · 92^((36 − AWG)/39), R = ρ(T)·L/A` | ASTM B258 gauge definition; annealed copper ρ = 1.724e-8 Ω·m |+| `rf` | dBm · watts · volts | — | `P = 10^((dBm − 30)/10) W, Vrms = √(P·Z), Vpp = 2√2·Vrms` | Sinusoid into a resistive load |+| `wavelength` | Wavelength & antenna lengths | — | `λ = c / (f·√εr)` | c = 299 792 458 m/s |+| `eseries` | Standard values & resistor codes | — | `IEC 60063 preferred numbers; IEC 60062 colour code; EIA-96 SMD code` | IEC 60063 / 60062, EIA-96 |+| `spacing` | Conductor spacing for voltage (IPC-2221 Table 6-1) | yes | `Table lookup up to 500 V; above 500 V: 500 V value + (V − 500) × per-volt increment` | IPC-2221B Table 6-1 (columns unchanged at sea level in IPC-2221C, Dec 2023); verified against two independent reproductions |+| `diffpair` | Differential pair impedance (edge-coupled) | yes | `Microstrip: Zdiff = 2·Z0·(1 − 0.48·e^(−0.96·s/h)) · Stripline: Zdiff = 2·Z0·(1 − 0.347·e^(−2.9·s/b))` | IPC-2141A / National Semiconductor AN-905 closed forms (±10 %; confirm with your fab's field solver) |+| `via` | Via: resistance, current, parasitics | yes | `A = π((d/2+t)² − (d/2)²), R = ρ·h/A, Imax: IPC-2221 external on A, L = 5.08·h·[ln(4h/d)+1] nH (h,d in in), C = 1.41·εr·T·D1/(D2 − D1) pF, Δt10-90 = 2.2·C·Z0/2` | Barrel geometry (as KiCad Via Size); L and C: H. Johnson & M. Graham, High-Speed Digital Design §7; thermal: k_Cu = 401 W/m·K |+| `fusing` | Fusing current (Onderdonk) | — | `I = A·√( log10(1 + (Tm − Ta)/(234 + Ta)) / (33·t) ), A in circular mils, Tm = 1083 °C (copper)` | Onderdonk equation (adiabatic; used by Saturn PCB Toolkit) |+| `bandwidth` | Rise time, bandwidth & critical length | — | `BW = 0.35/tr, f_knee = 0.5/tr, v = c/√εeff, critical length = tr·v/6` | H. Johnson, High-Speed Digital Design (1/6 rule of thumb) |+| `skin` | Skin depth | — | `δ = √(2ρ / (ω·µ0·µr))` | Classical skin effect; ρ at 20 °C (Cu 1.724e-8, Al 2.65e-8, Au 2.44e-8, Ag 1.59e-8 Ω·m) |+| `rlc` | Reactance & RLC resonance | yes | `XL = 2πfL, XC = 1/(2πfC), f0 = 1/(2π√LC), Q series = √(L/C)/R, Q parallel = R·√(C/L)` | Circuit theory |+| `combine` | Series / parallel combinations | yes | `R, L series: Σx · parallel: 1/Σ(1/x) · C: the reverse` | Circuit theory (inductors assume no mutual coupling) |+| `rfind` | Two-resistor combination finder | yes | `series: R = Ra + Rb, parallel: R = Ra·Rb/(Ra + Rb)` | Exhaustive search over the chosen E-series (as KiCad E-Series tool) |+| `attenuator` | Resistive attenuator (Pi / Tee) | yes | `K = 10^(dB/20) · Pi: Rshunt = Z(K+1)/(K−1), Rseries = Z(K²−1)/(2K) · Tee: Rseries = Z(K−1)/(K+1), Rshunt = 2ZK/(K²−1)` | Matched symmetric pads (as KiCad RF-Attenuators, Digi-Key attenuator calculator) |+| `vswr` | VSWR · return loss · mismatch loss | — | `\|Γ\| = (VSWR−1)/(VSWR+1) = 10^(−RL/20) = \|ZL−Z0\|/(ZL+Z0), RL = −20·log\|Γ\|, ML = −10·log(1−\|Γ\|²)` | Transmission-line theory (resistive load) |+| `regulator` | Adjustable regulator feedback resistors | yes | `Vout = Vref·(1 + R2/R1) + Iadj·R2` | TI LM317 datasheet (Vref 1.25 V, Iadj 50 µA typ); same form for switcher FB dividers with Iadj ≈ 0 |+| `mosfet` | MOSFET conduction & switching loss | yes | `Pcond = I²·Rds·k·D, Psw ≈ ½·V·I·(tr+tf)·fsw, Pgate = Qg·Vgs·fsw (in the driver)` | First-order hard-switching estimate (e.g. Infineon/TI MOSFET loss app notes) |+| `pdn` | PDN target impedance | — | `Z_target = V·ripple / ΔI` | L. D. Smith et al., "Power Distribution System Design Methodology" (target-impedance method) |+| `opamp` | Op-amp gain & bandwidth | yes | `non-inv: G = 1 + Rf/Rg · inv: G = −Rf/Rg · f−3dB = GBW/(1 + Rf/Rg) · full-power BW = SR/(2π·Vpk)` | Voltage-feedback op-amp, single-pole model |+| `timer555` | 555 timer | yes | `astable: f = 1.44/((RA+2RB)·C), tH = 0.693(RA+RB)C, tL = 0.693·RB·C · monostable: t = 1.1·R·C` | TI NE555 datasheet (SLFS022) |+| `ntc` | NTC thermistor (β model) | yes | `R(T) = R25·exp(β·(1/T − 1/298.15)), 1/T = 1/298.15 + ln(R/R25)/β` | β-parameter model (±1 °C typical over 0–100 °C; Steinhart-Hart is tighter) |+| `ppm` | Frequency tolerance (ppm) | — | `Δf = f·ppm/10⁶, drift per day = 86400·ppm/10⁶ s` | Definition |+| `spiral` | Planar spiral inductor | yes | `L = K1·µ0·n²·d_avg / (1 + K2·ρ), d_avg = (dout+din)/2, ρ = (dout−din)/(dout+din)` | Modified Wheeler: Mohan, Hershenson, Boyd & Lee, IEEE JSSC 34(10), 1999 (K1/K2: square 2.34/2.75, hex 2.33/3.82, oct 2.25/3.55) |+| `units` | Length & copper unit converter | — | `1 mil = 0.0254 mm, 1 oz/ft² Cu ≈ 34.8 µm (1.37 mil)` | Definitions |
bin/hwcalcadded+154@@ -0,0 +1,154 @@+#!/usr/bin/env node+/* hwcalc CLI. Global flag: --ai-thread "<name>" (required on verbs that change something). */+'use strict';+const fs = require('fs'), path = require('path'), os = require('os'), http = require('http'), { spawn, execFileSync } = require('child_process');+const DIR = path.resolve(fs.realpathSync(__filename), '..', '..');+const H = require(path.join(DIR, 'calcs.js')), PKG = require(path.join(DIR, 'package.json'));+const HOME = path.join(os.homedir(), '.adom', 'instances', 'hwcalc');++// ---- args: global flags anywhere+let argv = process.argv.slice(2); const flags = {};+const takeFlag = (name, hasVal = true) => { const i = argv.indexOf(name); if (i < 0) return undefined; const v = hasVal ? argv[i + 1] : true; argv.splice(i, hasVal ? 2 : 1); return v; };+flags.thread = takeFlag('--ai-thread') || process.env.ADOM_AI_THREAD || '';+flags.json = !!takeFlag('--json', false); flags.reason = takeFlag('--reason'); flags.surface = takeFlag('--surface');+flags.port = takeFlag('--port'); flags.ttl = takeFlag('--ttl'); flags.keepAlive = !!takeFlag('--keep-alive', false); flags.noShow = !!takeFlag('--no-show', false);+flags.newInst = !!takeFlag('--new', false); flags.svg = takeFlag('--svg');+const [verb, ...rest] = argv;++const say = (o, text) => { if (flags.json) console.log(JSON.stringify(typeof o === 'string' ? { ok: true, message: o } : o, null, 1)); else if (text) console.log(text); else console.log(typeof o === 'string' ? o : JSON.stringify(o, null, 1)); };+const die = (msg, hint, code = 'error') => { console.error(JSON.stringify({ ok: false, errorCode: code, error: msg, hint }, null, 1)); process.exit(1); };+const needThread = () => { if (!flags.thread) die('This app requires every AI caller to give its ai-thread name.',+ 'Re-run with the global flag: hwcalc --ai-thread "<name>" <verb>. Pick a short name a human would recognize for THIS conversation and reuse it on every Adom tool.', 'caller_identity_required'); };+const kv = list => Object.fromEntries(list.filter(a => a.includes('=')).map(a => { const i = a.indexOf('='); return [a.slice(0, i), a.slice(i + 1)]; }));++// ---- registry+function instances() {+ let out = [];+ try { for (const f of fs.readdirSync(HOME)) if (f.endsWith('.json') && f !== 'settings.json') {+ const p = path.join(HOME, f); let e; try { e = JSON.parse(fs.readFileSync(p, 'utf8')); } catch { continue; }+ let alive = false; try { process.kill(e.pid, 0); alive = true; } catch {}+ if (!alive) { try { fs.unlinkSync(p); } catch {} continue; }+ out.push(e); } } catch {}+ return out;+}+const proxyUrl = port => (process.env.VSCODE_PROXY_URI || 'http://localhost:{{port}}/').replace('{{port}}', port);+function req(port, method, p, body) {+ return new Promise((res, rej) => {+ const data = body ? JSON.stringify(body) : null;+ const r = http.request({ host: '127.0.0.1', port, method, path: p, headers: data ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } : {} }, rr => {+ let b = ''; rr.on('data', c => b += c); rr.on('end', () => { try { res(JSON.parse(b)); } catch { res({ ok: false, raw: b }); } }); });+ r.on('error', rej); if (data) r.write(data); r.end();+ });+}+function live() { const all = instances(); return all.find(e => e.thread === flags.thread) || all[0]; }+function requireLive() { const e = live(); if (!e) die('No hwcalc server is running.', 'Start one: hwcalc --ai-thread "<name>" start', 'not_running'); return e; }++async function show(port, surface) {+ const s = surface || (await req(port, 'GET', '/settings').catch(() => ({}))).settings?.default_surface || 'wv';+ const url = proxyUrl(port);+ if (s === 'pup') {+ execFileSync('adom-bridge-cli', ['--ai-thread', flags.thread || 'hwcalc', 'pup_open_window', JSON.stringify({ sessionId: 'hwcalc', profile: 'hwcalc', url })], { stdio: 'inherit' });+ } else {+ execFileSync('adom-cli', ['hydrogen', 'webview', 'open-or-refresh', '--name', 'Hardware Calculator', '--url', url], { stdio: flags.json ? 'ignore' : 'inherit' });+ }+ return { surface: s, url };+}++const HELP = `hwcalc ${PKG.version} — hardware design calculations (Adom app)++ hwcalc --ai-thread "<name>" start [--port auto|N] [--ttl H] [--keep-alive] [--no-show] [--new]+ hwcalc --ai-thread "<name>" show [--surface wv|pup]+ hwcalc ls list running instances (flags version drift)+ hwcalc list list calculators and their inputs+ hwcalc calc <id> key=value … [--svg f] compute (no server needed), e.g. hwcalc calc trace I=3 dT=20 oz=2; --svg writes the schematic+ hwcalc --ai-thread "<name>" open <id> key=value … show a calculation in the open UI+ hwcalc settings [--ai-thread "<name>" key=value …] read / change settings+ hwcalc state | console+ hwcalc --ai-thread "<name>" shutdown --reason "<why>"+ add --json for machine-readable output`;++(async () => {+ switch (verb) {+ case undefined: case 'help': case '--help': case '-h': return console.log(HELP);+ case '--version': case 'version': return say({ ok: true, app: 'hwcalc', version: PKG.version });+ case 'list': {+ const cat = H.catalog();+ if (flags.json) return say({ ok: true, calcs: cat });+ for (const c of cat) console.log(`${c.id.padEnd(11)} ${c.group.padEnd(12)} ${c.title}\n${' '.repeat(24)}inputs: ${c.inputs.map(f => f.key + (f.type === 'select' ? '=' + f.options.join('|') : f.unit ? `[${f.unit}]` : '')).join(' ')}`);+ return;+ }+ case 'calc': {+ const [id, ...pairs] = rest; if (!id) die('Name a calculator.', 'hwcalc list');+ const r = H.run(id, kv(pairs), (() => { try { return JSON.parse(fs.readFileSync(path.join(HOME, 'settings.json'), 'utf8')); } catch { return {}; } })());+ if (flags.svg) {+ const S = require(path.join(__dirname, '..', 'schematics.js')), svg = S.draw(id, kv(pairs));+ if (!svg) die(`No schematic for "${id}".`, 'schematics exist for: ' + S.ids.join(', '), 'no_schematic');+ fs.writeFileSync(flags.svg, svg); if (!flags.json) console.log(`schematic written to ${flags.svg}`);+ }+ if (flags.json) return say(r);+ if (!r.ok) die(r.error || 'failed', r.known ? 'known: ' + r.known.join(', ') : undefined);+ console.log(r.title); for (const o of r.outputs) console.log(` ${o.label.padEnd(34)} ${o.text}`);+ if (r.table) { console.log(' ' + r.table.head.join(' | ')); for (const row of r.table.rows) console.log(' ' + row.join(' | ')); }+ for (const w of r.warnings) console.log(' WARN: ' + w); for (const n of r.notes) console.log(' note: ' + n);+ console.log(` formula: ${r.formula}\n ref: ${r.ref}`); return;+ }+ case 'ls': {+ const all = instances();+ if (flags.json) return say({ ok: true, instances: all.map(e => ({ ...e, stale: e.version !== PKG.version })) });+ if (!all.length) return console.log('No hwcalc instances running.');+ for (const e of all) {+ const idle = Math.round((Date.now() - Date.parse(e.lastActivity)) / 60000);+ console.log(`port ${e.port} pid ${e.pid} thread "${e.thread}" v${e.version} idle ${idle} min ${proxyUrl(e.port)}`);+ if (e.version !== PKG.version) console.log(` WARN: runs ${e.version}, disk has ${PKG.version}. Shut it down and respawn.`);+ }+ return;+ }+ case 'start': {+ needThread();+ const mine = instances().find(e => e.thread === flags.thread), any = instances()[0];+ const reuse = mine || (!flags.newInst && any);+ if (reuse) {+ const note = reuse.thread === flags.thread ? '' : ` (owned by thread "${reuse.thread}"; the calculator keeps no per-thread state, so it is shared. Pass --new for a private one)`;+ say({ ok: true, reused: true, port: reuse.port, url: proxyUrl(reuse.port) }, `OK: already running on port ${reuse.port}${note}. Use that instance.`);+ if (!flags.noShow) await show(reuse.port, flags.surface);+ return;+ }+ const args = [path.join(DIR, 'server.js'), '--ai-thread', flags.thread, '--port', flags.port || 'auto'];+ if (flags.ttl) args.push('--ttl', flags.ttl); if (flags.keepAlive) args.push('--keep-alive');+ fs.mkdirSync(HOME, { recursive: true });+ const logf = fs.openSync(path.join(HOME, 'server.log'), 'a');+ const child = spawn(process.execPath, args, { detached: true, stdio: ['ignore', logf, logf] }); child.unref();+ let port = 0;+ for (let i = 0; i < 50 && !port; i++) { await new Promise(r => setTimeout(r, 100)); const e = instances().find(x => x.pid === child.pid); if (e && e.port) port = e.port; }+ if (!port) die('Server did not come up.', `See ${path.join(HOME, 'server.log')}`);+ say({ ok: true, started: true, port, pid: child.pid, url: proxyUrl(port) }, `OK: hwcalc ${PKG.version} started on port ${port} (pid ${child.pid}).`);+ if (!flags.noShow) await show(port, flags.surface);+ return;+ }+ case 'show': { needThread(); const e = requireLive(); const r = await show(e.port, flags.surface); return say({ ok: true, ...r }, `OK: shown on ${r.surface} (${r.url})`); }+ case 'open': {+ needThread(); const e = requireLive(); const [id, ...pairs] = rest;+ const r = await req(e.port, 'POST', '/api/open', { aiThread: flags.thread, calc: id, inputs: kv(pairs) });+ if (!r.ok) die(r.error, r.known ? 'known: ' + r.known.join(', ') : undefined);+ if (flags.json) return say(r);+ console.log(`OK: ${r.result.title} open in the UI (${r.clients} page${r.clients === 1 ? '' : 's'} connected)`);+ for (const o of r.result.outputs) console.log(` ${o.label.padEnd(34)} ${o.text}`); return;+ }+ case 'settings': {+ const e = requireLive(), patch = kv(rest);+ if (!Object.keys(patch).length) return say(await req(e.port, 'GET', '/settings'));+ needThread();+ for (const k of Object.keys(patch)) { if (patch[k] === 'true' || patch[k] === 'false') patch[k] = patch[k] === 'true'; else if (/^\d+(\.\d+)?$/.test(patch[k])) patch[k] = Number(patch[k]); }+ const r = await req(e.port, 'POST', '/settings', { aiThread: flags.thread, ...patch }); if (!r.ok) die(r.error, 'hwcalc settings (shows the valid values)', r.errorCode);+ return say(r);+ }+ case 'state': return say(await req(requireLive().port, 'GET', '/state'));+ case 'console': { const r = await req(requireLive().port, 'GET', '/console'); return flags.json ? say(r) : console.log(r.lines.join('\n')); }+ case 'shutdown': {+ needThread(); const e = requireLive();+ const r = await req(e.port, 'POST', '/shutdown', { aiThread: flags.thread, reason: flags.reason });+ if (!r.ok) die(r.error, r.hint, r.errorCode); return say(`OK: hwcalc on port ${e.port} shutting down.`);+ }+ default: die(`Unknown verb "${verb}".`, 'hwcalc help');+ }+})().catch(e => die(String(e.message || e)));
calcs.jsadded+894@@ -0,0 +1,894 @@+/* hwcalc — hardware design calculations. One module shared by the browser UI, the HTTP API and the CLI.+ * Every calculator names the formula and the reference it implements. Keep them honest: no fudge factors. */+(function (root, factory) {+ if (typeof module === 'object' && module.exports) module.exports = factory();+ else root.HWCALC = factory();+})(typeof self !== 'undefined' ? self : this, function () {+ 'use strict';++ // ---------------------------------------------------------------- number parsing / formatting+ const SI = { f: 1e-15, p: 1e-12, n: 1e-9, u: 1e-6, 'µ': 1e-6, m: 1e-3, k: 1e3, K: 1e3, M: 1e6, G: 1e9 };+ const UNIT_SUFFIX = /(ohms?|Ω|Hz|hz|F|H|V|A|W|s|°C|C)$/;++ /** Parse "4k7", "10u", "2.2M", "100nF", "1e-3". si=false means a plain number (mm, %, AWG...). */+ function parseNum(raw, si = true) {+ if (raw === null || raw === undefined) return NaN;+ if (typeof raw === 'number') return raw;+ let s = String(raw).trim().replace(/,/g, '');+ if (s === '') return NaN;+ if (!si) return Number(s);+ s = s.replace(UNIT_SUFFIX, '').trim();+ const mm = s.match(/^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\s*([fpnuµmkKMG]?)(\d*)$/);+ if (!mm) return Number(s);+ let [, num, pre, tail] = mm;+ if (tail && pre) num = num + '.' + tail; // 4k7 -> 4.7k+ else if (tail) return NaN;+ return Number(num) * (pre ? SI[pre] : 1);+ }++ const PREFIXES = [[1e9, 'G'], [1e6, 'M'], [1e3, 'k'], [1, ''], [1e-3, 'm'], [1e-6, 'µ'], [1e-9, 'n'], [1e-12, 'p'], [1e-15, 'f']];+ function fmtSI(v, unit = '', digits = 4) {+ if (v === null || v === undefined || Number.isNaN(v)) return '—';+ if (!Number.isFinite(v)) return (v > 0 ? '∞' : '−∞') + (unit ? ' ' + unit : '');+ if (v === 0) return '0' + (unit ? ' ' + unit : '');+ const a = Math.abs(v);+ let [scale, p] = PREFIXES.find(([s]) => a >= s * 0.9995) || PREFIXES[PREFIXES.length - 1];+ const n = v / scale;+ return `${trim(n.toPrecision(digits))} ${p}${unit}`.trim();+ }+ function fmtN(v, unit = '', dp = 3) {+ if (v === null || v === undefined || Number.isNaN(v)) return '—';+ if (!Number.isFinite(v)) return '∞';+ return `${trim(v.toFixed(dp))}${unit ? ' ' + unit : ''}`;+ }+ const trim = s => s.includes('e') ? s : s.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');++ // ---------------------------------------------------------------- E-series (IEC 60063)+ const E_BASE = {+ E3: [1.0, 2.2, 4.7],+ E6: [1.0, 1.5, 2.2, 3.3, 4.7, 6.8],+ E12: [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2],+ E24: [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1],+ };+ for (const n of [48, 96, 192]) { // E48+ follow round(10^(i/n), 3 s.f.), one documented exception+ const a = []; for (let i = 0; i < n; i++) a.push(Math.round(Math.pow(10, i / n) * 100) / 100);+ if (n === 192) a[a.indexOf(9.19)] = 9.20; // IEC 60063: 919 is listed as 920+ E_BASE['E' + n] = a;+ }+ const TOL = { E3: '>20%', E6: '20%', E12: '10%', E24: '5%', E48: '2%', E96: '1%', E192: '0.5%' };++ /** Nearest E-series values around v: {below, above, nearest}. */+ function eNearest(v, series = 'E24') {+ const base = E_BASE[series] || E_BASE.E24;+ if (!(v > 0)) return { below: NaN, above: NaN, nearest: NaN };+ const dec = Math.floor(Math.log10(v) + 1e-12), m = v / Math.pow(10, dec);+ const cand = [];+ for (const d of [dec - 1, dec, dec + 1]) for (const b of base) cand.push(+(b * Math.pow(10, d)).toPrecision(4));+ cand.sort((a, b) => a - b);+ let below = cand.filter(c => c <= v * (1 + 1e-9)).pop(), above = cand.find(c => c >= v * (1 - 1e-9));+ const nearest = (Math.abs(Math.log(v / below)) <= Math.abs(Math.log(above / v))) ? below : above;+ return { below, above, nearest };+ }+ function eValuesInRange(lo, hi, series) {+ const base = E_BASE[series] || E_BASE.E24, out = [];+ for (let d = Math.floor(Math.log10(lo)) - 1; d <= Math.ceil(Math.log10(hi)) + 1; d++)+ for (const b of base) { const x = +(b * Math.pow(10, d)).toPrecision(4); if (x >= lo && x <= hi) out.push(x); }+ return out.sort((a, b) => a - b);+ }++ // resistor colour code (IEC 60062)+ const COLOURS = ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white'];+ function colourBands(v, sig) {+ if (!(v > 0)) return [];+ const exp = Math.floor(Math.log10(v) + 1e-9) - (sig - 1);+ const digits = String(Math.round(v / Math.pow(10, exp))).padStart(sig, '0').slice(0, sig).split('').map(Number);+ const mult = exp >= 0 ? COLOURS[exp] : (exp === -1 ? 'gold' : exp === -2 ? 'silver' : '?');+ return [...digits.map(d => COLOURS[d]), mult];+ }+ // EIA-96 SMD code for E96 values+ const EIA96_MULT = { '-3': 'Z', '-2': 'Y', '-1': 'X', '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F' };+ function eia96(v) {+ const exp = Math.floor(Math.log10(v) + 1e-9) - 2, three = Math.round(v / Math.pow(10, exp));+ const idx = E_BASE.E96.findIndex(b => Math.round(b * 100) === three);+ return idx < 0 ? null : String(idx + 1).padStart(2, '0') + (EIA96_MULT[String(exp)] || '?');+ }+ function smd3(v) { // 3-digit code (E24, 5%): 472 = 4.7k; R for decimal < 10+ if (v < 10) return String(v).replace('.', 'R').slice(0, 3);+ const exp = Math.floor(Math.log10(v) + 1e-9) - 1; return String(Math.round(v / Math.pow(10, exp))).padStart(2, '0') + exp;+ }++ // ---------------------------------------------------------------- helpers+ const PI = Math.PI;+ const par = (a, b) => (!Number.isFinite(a) ? b : !Number.isFinite(b) ? a : (a * b) / (a + b));+ const out = (label, value, unit, opt = {}) => ({ label, value, unit, ...opt });+ const need = (v, keys) => keys.filter(k => !(Number.isFinite(v[k])));+ const RHO_CU = 1.724e-8, ALPHA_CU = 0.00393; // Ω·m at 20 °C, /°C (annealed copper)+ const OZ_UM = 34.79; // 1 oz/ft² copper ≈ 34.79 µm (1.37 mil)++ // ---------------------------------------------------------------- calculators+ const CALCS = [];+ const def = c => CALCS.push(c);++ def({ id: 'ohms', group: 'Basics', title: "Ohm's law & power",+ blurb: 'Enter any two of V, I, R, P; the other two are solved.',+ inputs: [+ { key: 'V', label: 'Voltage', unit: 'V', def: '5' },+ { key: 'I', label: 'Current', unit: 'A', def: '10m' },+ { key: 'R', label: 'Resistance', unit: 'Ω', def: '' },+ { key: 'P', label: 'Power', unit: 'W', def: '' }],+ formula: 'V = I·R, P = V·I = I²R = V²/R', ref: 'Ohm / Joule',+ compute(v) {+ const have = ['V', 'I', 'R', 'P'].filter(k => Number.isFinite(v[k]));+ if (have.length !== 2) return { error: 'Enter exactly two of V, I, R, P (leave the other two blank).' };+ let { V, I, R, P } = v; const h = have.join('');+ if (h === 'VI') { R = V / I; P = V * I; } else if (h === 'VR') { I = V / R; P = V * V / R; }+ else if (h === 'VP') { I = P / V; R = V * V / P; } else if (h === 'IR') { V = I * R; P = I * I * R; }+ else if (h === 'IP') { V = P / I; R = P / (I * I); } else if (h === 'RP') { V = Math.sqrt(P * R); I = Math.sqrt(P / R); }+ return { outputs: [out('Voltage', V, 'V'), out('Current', I, 'A'), out('Resistance', R, 'Ω'), out('Power', P, 'W')] };+ } });++ def({ id: 'divider', group: 'Basics', title: 'Voltage divider',+ blurb: 'Analyse a divider (optional load), or design one from standard values.',+ inputs: [+ { key: 'mode', label: 'Mode', type: 'select', options: ['analyse', 'design'], def: 'analyse' },+ { key: 'Vin', label: 'Input voltage', unit: 'V', def: '12' },+ { key: 'R1', label: 'R1 (top)', unit: 'Ω', def: '10k', show: 'analyse' },+ { key: 'R2', label: 'R2 (bottom)', unit: 'Ω', def: '3k3', show: 'analyse' },+ { key: 'RL', label: 'Load on output (blank = none)', unit: 'Ω', def: '', show: 'analyse' },+ { key: 'Vout', label: 'Target output', unit: 'V', def: '3.3', show: 'design' },+ { key: 'Rtot', label: 'Approx. total R1+R2', unit: 'Ω', def: '100k', show: 'design' },+ { key: 'series', label: 'E-series', type: 'select', options: ['E6', 'E12', 'E24', 'E48', 'E96', 'E192'], def: 'E24', show: 'design', setting: 'e_series' }],+ formula: 'Vout = Vin · (R2‖RL) / (R1 + R2‖RL), Rout = R1‖R2', ref: 'Kirchhoff',+ compute(v) {+ if (v.mode === 'design') {+ const miss = need(v, ['Vin', 'Vout', 'Rtot']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ if (!(v.Vout > 0 && v.Vout < v.Vin)) return { error: 'Target must be between 0 and Vin.' };+ const rows = [];+ for (const R2 of eValuesInRange(v.Rtot / 50, v.Rtot * 5, v.series)) {+ const R1 = eNearest(R2 * (v.Vin - v.Vout) / v.Vout, v.series).nearest;+ const Vo = v.Vin * R2 / (R1 + R2), tot = R1 + R2;+ if (tot < v.Rtot / 3 || tot > v.Rtot * 3) continue;+ rows.push({ R1, R2, Vo, err: (Vo - v.Vout) / v.Vout, tot });+ }+ rows.sort((a, b) => Math.abs(a.err) - Math.abs(b.err) || Math.abs(Math.log(a.tot / v.Rtot)) - Math.abs(Math.log(b.tot / v.Rtot)));+ const best = rows.slice(0, 6);+ if (!best.length) return { error: 'No pair found; widen the total resistance.' };+ return { outputs: [out('Best R1', best[0].R1, 'Ω'), out('Best R2', best[0].R2, 'Ω'), out('Output', best[0].Vo, 'V'), out('Error', best[0].err * 100, '%', { fmt: 'n', dp: 3 })],+ table: { head: ['R1', 'R2', 'Vout', 'Error', 'Divider current'], rows: best.map(r => [fmtSI(r.R1, 'Ω'), fmtSI(r.R2, 'Ω'), fmtSI(r.Vo, 'V'), fmtN(r.err * 100, '%', 3), fmtSI(v.Vin / r.tot, 'A')]) },+ notes: [`${v.series} (${TOL[v.series]} tolerance). Resistor tolerance adds up to ±${TOL[v.series]} of worst-case error on top of the nominal error shown.`] };+ }+ const miss = need(v, ['Vin', 'R1', 'R2']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ const R2e = par(v.R2, Number.isFinite(v.RL) ? v.RL : Infinity);+ const Vo = v.Vin * R2e / (v.R1 + R2e), I1 = v.Vin / (v.R1 + R2e);+ const Vnl = v.Vin * v.R2 / (v.R1 + v.R2);+ const o = [out('Output voltage', Vo, 'V'), out('Ratio', Vo / v.Vin, '', { fmt: 'n', dp: 5 }), out('Current through R1', I1, 'A'),+ out('Power R1', I1 * I1 * v.R1, 'W'), out('Power R2', (Vo * Vo) / v.R2, 'W'), out('Output (Thevenin) resistance', par(v.R1, v.R2), 'Ω')];+ const notes = [];+ if (Number.isFinite(v.RL)) notes.push(`Unloaded output would be ${fmtSI(Vnl, 'V')}; the load pulls it ${fmtN((Vo - Vnl) / Vnl * 100, '%', 2)}.`);+ return { outputs: o, notes };+ } });++ def({ id: 'led', group: 'Basics', title: 'LED series resistor',+ inputs: [+ { key: 'Vs', label: 'Supply voltage', unit: 'V', def: '5' },+ { key: 'Vf', label: 'LED forward voltage', unit: 'V', def: '2.0' },+ { key: 'n', label: 'LEDs in series', unit: '', def: '1', si: false },+ { key: 'If', label: 'LED current', unit: 'A', def: '5m' },+ { key: 'series', label: 'E-series', type: 'select', options: ['E12', 'E24', 'E96'], def: 'E24', setting: 'e_series' }],+ formula: 'R = (Vs − n·Vf) / If', ref: 'Ohm; use the datasheet Vf at the chosen If',+ compute(v) {+ const miss = need(v, ['Vs', 'Vf', 'n', 'If']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ const head = v.Vs - v.n * v.Vf; if (head <= 0) return { error: 'Supply is not above the total forward voltage.' };+ const R = head / v.If, Rs = eNearest(R, v.series).above, I = head / Rs;+ return { outputs: [out('Exact resistance', R, 'Ω'), out(`Next ${v.series} value up`, Rs, 'Ω', { highlight: true }), out('Actual current', I, 'A'),+ out('Resistor dissipation', I * I * Rs, 'W'), out('LED power (total)', v.n * v.Vf * I, 'W'), out('Efficiency', v.n * v.Vf / v.Vs * 100, '%', { fmt: 'n', dp: 1 })],+ notes: ['Vf varies with current, temperature and bin; the rounded-up resistor keeps the current at or below target.'] };+ } });++ def({ id: 'filter', group: 'Signal', title: 'RC / RL / LC time constants & cut-off',+ inputs: [+ { key: 'mode', label: 'Network', type: 'select', options: ['RC', 'RL', 'LC'], def: 'RC' },+ { key: 'R', label: 'Resistance', unit: 'Ω', def: '10k', show: ['RC', 'RL'] },+ { key: 'C', label: 'Capacitance', unit: 'F', def: '100n', show: ['RC', 'LC'] },+ { key: 'L', label: 'Inductance', unit: 'H', def: '10u', show: ['RL', 'LC'] }],+ formula: 'RC: fc = 1/(2πRC), τ = RC · RL: fc = R/(2πL), τ = L/R · LC: f0 = 1/(2π√(LC)), Z0 = √(L/C)', ref: 'First-order / second-order networks',+ compute(v) {+ if (v.mode === 'LC') {+ const miss = need(v, ['L', 'C']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ return { outputs: [out('Resonant frequency', 1 / (2 * PI * Math.sqrt(v.L * v.C)), 'Hz', { highlight: true }), out('Characteristic impedance √(L/C)', Math.sqrt(v.L / v.C), 'Ω'), out('Angular frequency', 1 / Math.sqrt(v.L * v.C), 'rad/s')] };+ }+ const tau = v.mode === 'RC' ? v.R * v.C : v.L / v.R;+ if (!Number.isFinite(tau)) return { error: 'Need R and ' + (v.mode === 'RC' ? 'C' : 'L') };+ return { outputs: [out('−3 dB cut-off', 1 / (2 * PI * tau), 'Hz', { highlight: true }), out('Time constant τ', tau, 's'),+ out('Rise time 10–90 % (2.2τ)', 2.2 * tau, 's'), out('Settle to 1 % (4.6τ)', 4.6 * tau, 's'), out('Settle to 0.1 % (6.9τ)', 6.9 * tau, 's')] };+ } });++ def({ id: 'trace', group: 'PCB', title: 'Trace width for current (IPC-2152 / IPC-2221)',+ blurb: 'Width for a current and temperature rise, or the current a given width carries. Plus DC resistance and drop.',+ inputs: [+ { key: 'std', label: 'Standard', type: 'select', options: ['IPC-2152 (baseline chart)', 'IPC-2221'], def: 'IPC-2152 (baseline chart)' },+ { key: 'mode', label: 'Solve for', type: 'select', options: ['width', 'current'], def: 'width' },+ { key: 'I', label: 'Current', unit: 'A', def: '2', show: 'width' },+ { key: 'w', label: 'Trace width', unit: 'mm', def: '0.5', si: false, show: 'current' },+ { key: 'dT', label: 'Temperature rise', unit: '°C', def: '10', si: false, setting: 'trace_dT' },+ { key: 'oz', label: 'Copper weight', unit: 'oz', def: '1', si: false },+ { key: 'layer', label: 'Layer (IPC-2221 only)', type: 'select', options: ['external', 'internal'], def: 'external', show: 'IPC-2221' },+ { key: 'len', label: 'Trace length', unit: 'mm', def: '50', si: false },+ { key: 'Ta', label: 'Ambient', unit: '°C', def: '25', si: false }],+ formula: 'IPC-2152 baseline: A = (117.555·ΔT^−0.913 + 1.15)·I^(0.84·ΔT^−0.108 + 1.159) · IPC-2221: I = k·ΔT^0.44·A^0.725 (k 0.048 ext / 0.024 int) · A in mil²; R = ρ(T)·L/(w·t)',+ ref: 'IPC-2152 (2009, current revision) baseline chart via the published curve fit on smps.us; IPC-2221C (2023) §6.2 retains the IPC-2221 chart fit. ρCu = 1.724e-8 Ω·m, α = 0.00393/°C',+ compute(v) {+ const k = v.layer === 'internal' ? 0.024 : 0.048, t_mil = v.oz * OZ_UM / 25.4, t_m = v.oz * OZ_UM * 1e-6;+ const is2152 = String(v.std || '').startsWith('IPC-2152');+ const A_of = I => is2152 ? (117.555 * Math.pow(v.dT, -0.913) + 1.15) * Math.pow(I, 0.84 * Math.pow(v.dT, -0.108) + 1.159) : Math.pow(I / (k * Math.pow(v.dT, 0.44)), 1 / 0.725);+ let I, w_mm;+ if (v.mode === 'current') {+ const miss = need(v, ['w', 'dT', 'oz']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ w_mm = v.w; const A = w_mm / 0.0254 * t_mil;+ if (is2152) { let lo = 0, hi = 200; for (let i = 0; i < 100; i++) { const m = (lo + hi) / 2; if (A_of(m) < A) lo = m; else hi = m; } I = (lo + hi) / 2; }+ else I = k * Math.pow(v.dT, 0.44) * Math.pow(A, 0.725);+ } else {+ const miss = need(v, ['I', 'dT', 'oz']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ I = v.I; w_mm = A_of(I) / t_mil * 0.0254;+ }+ const T = (Number.isFinite(v.Ta) ? v.Ta : 25) + v.dT, rho = RHO_CU * (1 + ALPHA_CU * (T - 20));+ const R = Number.isFinite(v.len) ? rho * (v.len / 1000) / ((w_mm / 1000) * t_m) : NaN;+ const o = [v.mode === 'width' ? out('Minimum width', w_mm, 'mm', { fmt: 'n', dp: 3, highlight: true }) : out('Maximum current', I, 'A', { highlight: true }),+ out('Width', w_mm / 0.0254, 'mil', { fmt: 'n', dp: 1 }), out('Copper thickness', v.oz * OZ_UM, 'µm', { fmt: 'n', dp: 1 }),+ out('Cross-section', (w_mm / 0.0254) * t_mil, 'mil²', { fmt: 'n', dp: 1 })];+ if (Number.isFinite(R)) o.push(out(`Resistance at ${fmtN(T, '°C', 0)}`, R, 'Ω'), out('Voltage drop', R * I, 'V'), out('Power in trace', I * I * R, 'W'));+ const warn = [];+ if (is2152) { if (I > 30) warn.push('IPC-2152 test data stops at 30 A.'); if (v.dT < 2 || v.dT > 100) warn.push('The IPC-2152 fit covers ΔT 2–100 °C.'); }+ else { if (I > 35) warn.push('IPC-2221 curves stop at 35 A.'); if (v.dT < 10 || v.dT > 100) warn.push('IPC-2221 fit covers ΔT 10–100 °C.'); }+ const note = is2152+ ? 'IPC-2152 baseline = the standard\'s conservative universal chart (single trace, still air, no nearby plane; 0.070 in polyimide, 3 oz). The standard\'s modifiers for board thickness, copper planes and copper weight usually allow a NARROWER trace; the internal/external distinction of IPC-2221 does not apply. Same current for internal and external layers.'+ : 'IPC-2221 is the legacy 1950s-data chart kept in IPC-2221C. It is often too conservative for internal layers; prefer IPC-2152 for new designs.';+ return { outputs: o, warnings: warn, notes: [note] };+ } });++ def({ id: 'impedance', group: 'PCB', title: 'Microstrip / stripline impedance (IPC-2141)',+ inputs: [+ { key: 'geom', label: 'Geometry', type: 'select', options: ['microstrip', 'stripline'], def: 'microstrip' },+ { key: 'mode', label: 'Solve for', type: 'select', options: ['impedance', 'width'], def: 'impedance' },+ { key: 'w', label: 'Trace width', unit: 'mm', def: '0.3', si: false, show: 'impedance' },+ { key: 'Z', label: 'Target impedance', unit: 'Ω', def: '50', show: 'width' },+ { key: 'h', label: 'Dielectric height (microstrip: to plane; stripline: plane-to-plane b)', unit: 'mm', def: '0.2', si: false },+ { key: 'oz', label: 'Copper weight', unit: 'oz', def: '1', si: false },+ { key: 'er', label: 'Relative permittivity εr', unit: '', def: '4.3', si: false }],+ formula: 'Microstrip: Z0 = 87/√(εr+1.41)·ln(5.98h/(0.8w+t)) · Stripline: Z0 = 60/√εr·ln(1.9b/(0.8w+t))', ref: 'IPC-2141 closed forms (±5–10 %; use a field solver for final stack-ups)',+ compute(v) {+ const t = v.oz * OZ_UM / 1000, ms = v.geom === 'microstrip';+ const Zof = w => ms ? 87 / Math.sqrt(v.er + 1.41) * Math.log(5.98 * v.h / (0.8 * w + t)) : 60 / Math.sqrt(v.er) * Math.log(1.9 * v.h / (0.8 * w + t));+ let w = v.w;+ if (v.mode === 'width') {+ let lo = 0.005 * v.h, hi = 20 * v.h;+ if (!(Zof(lo) > v.Z && Zof(hi) < v.Z)) return { error: 'Target impedance is out of reach for this stack-up.' };+ for (let i = 0; i < 80; i++) { const m = (lo + hi) / 2; if (Zof(m) > v.Z) lo = m; else hi = m; } w = (lo + hi) / 2;+ }+ const Z = Zof(w);+ const tpd = ms ? 85 * Math.sqrt(0.475 * v.er + 0.67) : 85 * Math.sqrt(v.er); // ps/inch+ const o = [v.mode === 'width' ? out('Trace width', w, 'mm', { fmt: 'n', dp: 4, highlight: true }) : out('Impedance Z0', Z, 'Ω', { fmt: 'n', dp: 2, highlight: true }),+ out('Width', w / 0.0254, 'mil', { fmt: 'n', dp: 2 }), out('w/h', w / v.h, '', { fmt: 'n', dp: 3 }),+ out('Propagation delay', tpd / 25.4, 'ps/mm', { fmt: 'n', dp: 2 }), out('Effective εr', Math.pow(tpd / 84.73, 2), '', { fmt: 'n', dp: 2 })];+ const warn = [];+ if (ms && (w / v.h < 0.1 || w / v.h > 2.0)) warn.push('Microstrip formula is valid for 0.1 < w/h < 2.0.');+ if (!ms && (w / v.h > 0.35 || t / v.h > 0.25)) warn.push('Stripline formula is valid for w/b < 0.35 and t/b < 0.25.');+ if (v.er < 1 || v.er > 15) warn.push('Formula is valid for 1 < εr < 15.');+ return { outputs: o, warnings: warn };+ } });++ def({ id: 'ldo', group: 'Power', title: 'Linear regulator dissipation',+ inputs: [+ { key: 'Vin', label: 'Input voltage', unit: 'V', def: '5' },+ { key: 'Vout', label: 'Output voltage', unit: 'V', def: '3.3' },+ { key: 'Iout', label: 'Load current', unit: 'A', def: '300m' },+ { key: 'Iq', label: 'Quiescent / ground current', unit: 'A', def: '55u' },+ { key: 'theta', label: 'θJA (datasheet, your layout)', unit: '°C/W', def: '184', si: false },+ { key: 'Ta', label: 'Ambient', unit: '°C', def: '25', si: false },+ { key: 'Tjmax', label: 'Max junction', unit: '°C', def: '125', si: false }],+ formula: 'Pd = (Vin − Vout)·Iout + Vin·Iq, Tj = Ta + Pd·θJA', ref: 'Standard LDO thermal model (θJA is layout-dependent)',+ compute(v) {+ const miss = need(v, ['Vin', 'Vout', 'Iout', 'theta', 'Ta']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ const Iq = Number.isFinite(v.Iq) ? v.Iq : 0, Pd = (v.Vin - v.Vout) * v.Iout + v.Vin * Iq, Tj = v.Ta + Pd * v.theta;+ const Imax = ((v.Tjmax - v.Ta) / v.theta - v.Vin * Iq) / (v.Vin - v.Vout);+ const warn = Tj > v.Tjmax ? [`Junction exceeds ${v.Tjmax} °C: reduce the drop, add copper, or use a switcher.`] : [];+ return { outputs: [out('Dissipation', Pd, 'W', { highlight: true }), out('Junction temperature', Tj, '°C', { fmt: 'n', dp: 1 }),+ out('Margin to Tjmax', v.Tjmax - Tj, '°C', { fmt: 'n', dp: 1 }), out('Efficiency', v.Vout * v.Iout / (v.Vin * (v.Iout + Iq)) * 100, '%', { fmt: 'n', dp: 1 }),+ out('Max load current at Tjmax', Imax, 'A')], warnings: warn };+ } });++ def({ id: 'buck', group: 'Power', title: 'Buck converter: inductor & ripple',+ inputs: [+ { key: 'Vin', label: 'Max input voltage', unit: 'V', def: '12' },+ { key: 'Vout', label: 'Output voltage', unit: 'V', def: '3.3' },+ { key: 'Iout', label: 'Output current', unit: 'A', def: '2' },+ { key: 'fsw', label: 'Switching frequency', unit: 'Hz', def: '500k' },+ { key: 'rip', label: 'Inductor ripple (% of Iout)', unit: '%', def: '30', si: false },+ { key: 'eff', label: 'Estimated efficiency', unit: '%', def: '90', si: false },+ { key: 'Cout', label: 'Output capacitance', unit: 'F', def: '44u' },+ { key: 'esr', label: 'Output cap ESR', unit: 'Ω', def: '5m' }],+ formula: 'D = Vout/(Vin·η), L = Vout·(Vin−Vout)/(ΔIL·fsw·Vin), ΔVout = ΔIL/(8·fsw·Cout) + ΔIL·ESR', ref: 'TI SLVA477B (basic buck power stage)',+ compute(v) {+ const miss = need(v, ['Vin', 'Vout', 'Iout', 'fsw', 'rip']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ if (v.Vout >= v.Vin) return { error: 'Buck needs Vout < Vin.' };+ const eta = (v.eff || 90) / 100, D = v.Vout / (v.Vin * eta), dI = v.rip / 100 * v.Iout;+ const L = v.Vout * (v.Vin - v.Vout) / (dI * v.fsw * v.Vin);+ const o = [out('Duty cycle', D * 100, '%', { fmt: 'n', dp: 1 }), out('Minimum inductance', L, 'H', { highlight: true }), out('Ripple current ΔIL', dI, 'A'),+ out('Peak inductor / switch current', v.Iout + dI / 2, 'A'), out('Inductor RMS (≈)', Math.sqrt(v.Iout ** 2 + dI ** 2 / 12), 'A')];+ if (Number.isFinite(v.Cout)) o.push(out('Output ripple', dI / (8 * v.fsw * v.Cout) + (Number.isFinite(v.esr) ? dI * v.esr : 0), 'V'));+ return { outputs: o, notes: ['Use the MAXIMUM input voltage for L (worst ripple). Choose an inductor saturation rating above the peak current, and check the controller datasheet: many fix the ripple ratio.'] };+ } });++ def({ id: 'boost', group: 'Power', title: 'Boost converter: inductor & ripple',+ inputs: [+ { key: 'Vin', label: 'Min input voltage', unit: 'V', def: '3.3' },+ { key: 'Vout', label: 'Output voltage', unit: 'V', def: '12' },+ { key: 'Iout', label: 'Output current', unit: 'A', def: '500m' },+ { key: 'fsw', label: 'Switching frequency', unit: 'Hz', def: '600k' },+ { key: 'rip', label: 'Inductor ripple (% of inductor current)', unit: '%', def: '30', si: false },+ { key: 'eff', label: 'Estimated efficiency', unit: '%', def: '85', si: false },+ { key: 'Cout', label: 'Output capacitance', unit: 'F', def: '22u' },+ { key: 'esr', label: 'Output cap ESR', unit: 'Ω', def: '5m' }],+ formula: 'D = 1 − Vin·η/Vout, L = Vin·(Vout−Vin)/(ΔIL·fsw·Vout), ΔVout = Iout·D/(fsw·Cout) + ESR·Ipk', ref: 'TI SLVA372C (basic boost power stage)',+ compute(v) {+ const miss = need(v, ['Vin', 'Vout', 'Iout', 'fsw', 'rip']); if (miss.length) return { error: 'Need ' + miss.join(', ') };+ if (v.Vout <= v.Vin) return { error: 'Boost needs Vout > Vin.' };+ const eta = (v.eff || 85) / 100, D = 1 - v.Vin * eta / v.Vout, IL = v.Iout / (1 - D), dI = v.rip / 100 * IL;+ const L = v.Vin * (v.Vout - v.Vin) / (dI * v.fsw * v.Vout), Ipk = IL + dI / 2;+ const o = [out('Duty cycle', D * 100, '%', { fmt: 'n', dp: 1 }), out('Minimum inductance', L, 'H', { highlight: true }), out('Average inductor current', IL, 'A'),+ out('Ripple current ΔIL', dI, 'A'), out('Peak switch current', Ipk, 'A'), out('Input power', v.Vout * v.Iout / eta, 'W')];+ if (Number.isFinite(v.Cout)) o.push(out('Output ripple', v.Iout * D / (v.fsw * v.Cout) + (Number.isFinite(v.esr) ? v.esr * Ipk : 0), 'V'));+ return { outputs: o, notes: ['Use the MINIMUM input voltage (highest duty and current). Check the switch current limit against the peak.'] };+ } });++ def({ id: 'holdup', group: 'Power', title: 'Hold-up / bulk capacitor',+ inputs: [+ { key: 'mode', label: 'Solve for', type: 'select', options: ['time', 'capacitance'], def: 'capacitance' },+ { key: 'load', label: 'Load type', type: 'select', options: ['constant power', 'constant current'], def: 'constant power' },+ { key: 'P', label: 'Load power', unit: 'W', def: '2', show: 'constant power' },+ { key: 'I', label: 'Load current', unit: 'A', def: '100m', show: 'constant current' },+ { key: 'V1', label: 'Start voltage', unit: 'V', def: '12' },+ { key: 'V2', label: 'Minimum usable voltage', unit: 'V', def: '9' },+ { key: 'C', label: 'Capacitance', unit: 'F', def: '1m', show: 'time' },+ { key: 't', label: 'Required hold-up time', unit: 's', def: '10m', show: 'capacitance' }],+ formula: 'Constant P: t = C·(V1² − V2²)/(2P) · Constant I: t = C·(V1 − V2)/I', ref: 'Capacitor energy E = ½CV²',+ compute(v) {+ const cp = v.load === 'constant power', dV2 = v.V1 * v.V1 - v.V2 * v.V2, dV = v.V1 - v.V2;+ if (!(dV > 0)) return { error: 'Start voltage must exceed the minimum.' };+ const o = [];+ if (v.mode === 'time') {+ const t = cp ? v.C * dV2 / (2 * v.P) : v.C * dV / v.I; o.push(out('Hold-up time', t, 's', { highlight: true }));+ o.push(out('Usable energy', 0.5 * v.C * dV2, 'J'));+ } else {+ const C = cp ? 2 * v.P * v.t / dV2 : v.I * v.t / dV; o.push(out('Required capacitance', C, 'F', { highlight: true }));+ o.push(out('Usable energy', 0.5 * C * dV2, 'J'), out('Stored at start', 0.5 * C * v.V1 * v.V1, 'J'));+ }+ return { outputs: o, notes: ['Add margin for capacitance tolerance, ageing and DC-bias derating (ceramics can lose 50 %+ at rated voltage).'] };+ } });++ def({ id: 'battery', group: 'Power', title: 'Battery life (duty-cycled load)',+ inputs: [+ { key: 'cap', label: 'Battery capacity', unit: 'mAh', def: '2000', si: false },+ { key: 'Ia', label: 'Active current', unit: 'A', def: '25m' },+ { key: 'Is', label: 'Sleep current', unit: 'A', def: '15u' },+ { key: 'duty', label: 'Active duty cycle', unit: '%', def: '2', si: false },+ { key: 'derate', label: 'Usable capacity', unit: '%', def: '85', si: false }],+ formula: 'Iavg = Ia·d + Is·(1−d), life = C·derate / Iavg', ref: 'Charge balance (ignores self-discharge and temperature)',+ compute(v) {+ const d = v.duty / 100, Iavg = v.Ia * d + v.Is * (1 - d), h = (v.cap / 1000) * (v.derate / 100) / Iavg;+ return { outputs: [out('Average current', Iavg, 'A'), out('Battery life', h, 'h', { fmt: 'n', dp: 1, highlight: true }),+ out('…in days', h / 24, 'days', { fmt: 'n', dp: 1 }), out('…in years', h / 8766, 'years', { fmt: 'n', dp: 2 })],+ notes: ['Self-discharge dominates past about a year for many chemistries; include it for long-life designs.'] };+ } });++ def({ id: 'i2c', group: 'Interfaces', title: 'I²C pull-up resistor range',+ inputs: [+ { key: 'VDD', label: 'Pull-up supply', unit: 'V', def: '3.3' },+ { key: 'Cb', label: 'Bus capacitance', unit: 'F', def: '100p' },+ { key: 'speed', label: 'Mode', type: 'select', options: ['Standard 100 kHz', 'Fast 400 kHz', 'Fast-mode Plus 1 MHz'], def: 'Fast 400 kHz' }],+ formula: 'Rmin = (VDD − VOL)/IOL, Rmax = tr / (0.8473·Cb)', ref: 'NXP UM10204 §7.1 (tr max 1000/300/120 ns; IOL 3/3/20 mA; VOL 0.4 V, or 0.2·VDD below 2 V)',+ compute(v) {+ const spec = { 'Standard 100 kHz': [1000e-9, 3e-3], 'Fast 400 kHz': [300e-9, 3e-3], 'Fast-mode Plus 1 MHz': [120e-9, 20e-3] }[v.speed];+ const VOL = v.VDD > 2 ? 0.4 : 0.2 * v.VDD, Rmin = (v.VDD - VOL) / spec[1], Rmax = spec[0] / (0.8473 * v.Cb);+ const o = [out('Minimum pull-up', Rmin, 'Ω'), out('Maximum pull-up', Rmax, 'Ω')];+ const warn = [];+ if (Rmin > Rmax) warn.push('No resistor satisfies both limits: reduce bus capacitance, lower the speed, or use an active pull-up / buffer.');+ else { const pick = eValuesInRange(Rmin, Rmax, 'E24'); const g = Math.sqrt(Rmin * Rmax);+ if (pick.length) o.push(out('Suggested E24', pick.reduce((a, b) => Math.abs(Math.log(b / g)) < Math.abs(Math.log(a / g)) ? b : a), 'Ω', { highlight: true })); }+ if (v.Cb > (v.speed.startsWith('Fast-mode Plus') ? 550e-12 : 400e-12)) warn.push('Bus capacitance exceeds the spec limit for this mode.');+ return { outputs: o, warnings: warn, notes: ['Estimate Cb as ~10 pF per device pin plus trace/cable capacitance.'] };+ } });++ def({ id: 'crystal', group: 'Interfaces', title: 'Crystal oscillator load capacitors (CL)',+ blurb: 'Pierce oscillator: load caps for a crystal\'s rated CL, or the CL your caps give; with optional start-up margin, pulling and drive level.',+ inputs: [+ { key: 'mode', label: 'Mode', type: 'select', options: ['caps for target CL', 'CL from C1/C2'], def: 'caps for target CL' },+ { key: 'CL', label: 'Crystal rated load capacitance CL (datasheet)', unit: 'F', def: '12p' },+ { key: 'Cs', label: 'Stray capacitance Cs (pins + traces)', unit: 'F', def: '4p' },+ { key: 'series', label: 'E-series for C1 = C2', type: 'select', options: ['E6', 'E12', 'E24'], def: 'E12', show: 'caps for target CL' },+ { key: 'C1', label: 'C1 (OSC_IN side)', unit: 'F', def: '18p', show: 'CL from C1/C2' },+ { key: 'C2', label: 'C2 (OSC_OUT side)', unit: 'F', def: '18p', show: 'CL from C1/C2' },+ { key: 'F', label: 'Crystal frequency (for gm, drive level)', unit: 'Hz', def: '8M' },+ { key: 'C0', label: 'Shunt capacitance C0 (optional)', unit: 'F', def: '' },+ { key: 'ESR', label: 'ESR max (optional)', unit: 'Ω', def: '' },+ { key: 'gm', label: 'MCU oscillator gm (optional, A/V)', unit: 'A/V', def: '' },+ { key: 'Cm', label: 'Motional capacitance C1m (optional, for pulling)', unit: 'F', def: '' },+ { key: 'Vpp', label: 'Measured Vpp at OSC_IN (optional, for drive level)', unit: 'V', def: '' },+ { key: 'Cp', label: 'Scope probe capacitance', unit: 'F', def: '1p' },+ { key: 'DLmax', label: 'Crystal max drive level (optional)', unit: 'W', def: '' }],+ formula: 'CL = C1·C2/(C1+C2) + Cs → C1 = C2 = 2·(CL − Cs)\ngm_crit = 4·ESR·(2πF)²·(C0 + CL)², gain margin = gm/gm_crit ≥ 5\n' ++ 'pulling Δf/f = Cm/(2(C0+CL)), trim sensitivity = −Cm/(2(C0+CL)²)\nDL = ESR·IQ², IQ = 2πF·(Vpp/2√2)·(C1 + Cs/2 + Cprobe)',+ ref: 'ST AN2867 Rev 10 §3.3–3.5 (CL, gm_crit, gain margin ≥ 5, drive level); pulling / trim sensitivity from the crystal equivalent circuit (CTS, ECS crystal notes)',+ compute(v) {+ const o = [], warnings = [], notes = [];+ if (!(v.CL > 0) || !(v.Cs >= 0)) return { error: 'Enter the crystal load capacitance and the stray capacitance.' };+ let C1, C2, CLa;+ if (v.mode === 'caps for target CL') {+ const C = 2 * (v.CL - v.Cs); if (!(C > 0)) return { error: 'Stray capacitance exceeds the load capacitance: no external caps can reach this CL.' };+ const Cn = eNearest(C, v.series).nearest; C1 = C2 = Cn; CLa = Cn / 2 + v.Cs;+ o.push(out('Exact C1 = C2', C, 'F'), out(`Nearest ${v.series} C1 = C2`, Cn, 'F', { highlight: true }));+ } else {+ C1 = v.C1; C2 = v.C2; if (!(C1 > 0 && C2 > 0)) return { error: 'Enter C1 and C2.' };+ CLa = par(C1, C2) + v.Cs;+ }+ o.push(out('Load the crystal sees', CLa, 'F', { highlight: v.mode !== 'caps for target CL' }), out('Load error vs rated CL', (CLa - v.CL) / v.CL * 100, '%', { fmt: 'n', dp: 1 }));+ if (Number.isFinite(v.C0) && Number.isFinite(v.Cm)) {+ const pull = CL => v.Cm / (2 * (v.C0 + CL)) * 1e6;+ o.push(out('Frequency offset from load error', pull(CLa) - pull(v.CL), 'ppm', { fmt: 'n', dp: 2 }),+ out('Trim sensitivity at this load', -v.Cm / (2 * Math.pow(v.C0 + CLa, 2)) * 1e-12 * 1e6, 'ppm/pF', { fmt: 'n', dp: 2 }));+ }+ if (Number.isFinite(v.C0) && Number.isFinite(v.ESR) && v.F > 0) {+ const gmc = 4 * v.ESR * Math.pow(2 * PI * v.F, 2) * Math.pow(v.C0 + v.CL, 2);+ o.push(out('gm_crit', gmc, 'A/V'));+ if (Number.isFinite(v.gm)) {+ const gmm = v.gm / gmc; o.push(out('Gain margin gm/gm_crit', gmm, '', { fmt: 'n', dp: 1 }));+ if (gmm < 5) warnings.push(`Gain margin ${gmm.toFixed(1)} is below 5: start-up is not guaranteed over temperature and tolerance. Pick a crystal with lower ESR or lower CL (AN2867 §3.4).`);+ } else notes.push('Enter the MCU oscillator gm to get the gain margin; if the datasheet gives gm_crit_max instead, it must exceed gm_crit (gm_crit_max = gm/5).');+ }+ if (Number.isFinite(v.Vpp) && Number.isFinite(v.ESR) && v.F > 0) {+ const Ctot = C1 + v.Cs / 2 + (Number.isFinite(v.Cp) ? v.Cp : 0), IQ = 2 * PI * v.F * (v.Vpp / (2 * Math.SQRT2)) * Ctot, DL = v.ESR * IQ * IQ;+ o.push(out('Crystal current IQ (RMS)', IQ, 'A'), out('Drive level', DL, 'W'));+ if (Number.isFinite(v.DLmax)) {+ o.push(out('Max IQ peak-to-peak for DLmax', 2 * Math.SQRT2 * Math.sqrt(v.DLmax / v.ESR), 'A'));+ if (DL > v.DLmax) warnings.push('Drive level exceeds the crystal maximum: add a series resistor RExt on OSC_OUT (AN2867 §3.5.3).');+ }+ }+ notes.push('Stray capacitance is typically 2–5 pF (MCU pin capacitance plus traces); confirm against a frequency measurement and trim C1/C2.');+ return { outputs: o, warnings, notes };+ } });++ def({ id: 'shunt', group: 'Measurement', title: 'Current-sense shunt',+ inputs: [+ { key: 'I', label: 'Full-scale current', unit: 'A', def: '10' },+ { key: 'R', label: 'Shunt resistance', unit: 'Ω', def: '5m' },+ { key: 'G', label: 'Amplifier gain', unit: 'V/V', def: '50', si: false },+ { key: 'bits', label: 'ADC bits', unit: '', def: '12', si: false },+ { key: 'Vref', label: 'ADC reference', unit: 'V', def: '3.3' }],+ formula: 'Vsense = I·R, P = I²R, Vout = G·I·R, LSB current = Vref/(2^N·G·R)', ref: 'Ohm / Joule',+ compute(v) {+ const Vs = v.I * v.R, Vo = v.G * Vs, lsb = v.Vref / Math.pow(2, v.bits) / (v.G * v.R);+ const warn = Vo > v.Vref ? [`Amplifier output (${fmtSI(Vo, 'V')}) exceeds the ADC reference: full scale is ${fmtSI(v.Vref / (v.G * v.R), 'A')}.`] : [];+ return { outputs: [out('Sense voltage', Vs, 'V'), out('Shunt dissipation', v.I * v.I * v.R, 'W', { highlight: true }), out('Amplifier output', Vo, 'V'),+ out('Current per ADC LSB', lsb, 'A'), out('Usable full scale', Math.min(v.I, v.Vref / (v.G * v.R)), 'A')], warnings: warn,+ notes: ['Derate the shunt power rating (often to 50–70 %) and route the sense lines Kelvin-connected to the pads.'] };+ } });++ def({ id: 'adc', group: 'Measurement', title: 'ADC resolution & ideal SNR',+ inputs: [+ { key: 'bits', label: 'Resolution', unit: 'bits', def: '12', si: false },+ { key: 'Vref', label: 'Full-scale / reference', unit: 'V', def: '3.3' },+ { key: 'Vin', label: 'Input voltage (for code)', unit: 'V', def: '1.65' }],+ formula: 'LSB = Vref/2^N, code = ⌊Vin/LSB⌋, SNR = 6.02N + 1.76 dB, q-noise = LSB/√12', ref: 'Ideal quantiser',+ compute(v) {+ const lsb = v.Vref / Math.pow(2, v.bits);+ return { outputs: [out('LSB size', lsb, 'V', { highlight: true }), out('Code for input', Math.min(Math.pow(2, v.bits) - 1, Math.floor(v.Vin / lsb)), '', { fmt: 'n', dp: 0 }),+ out('Ideal SNR', 6.02 * v.bits + 1.76, 'dB', { fmt: 'n', dp: 2 }), out('Quantisation noise (RMS)', lsb / Math.sqrt(12), 'V'), out('Dynamic range', 20 * Math.log10(Math.pow(2, v.bits)), 'dB', { fmt: 'n', dp: 1 })] };+ } });++ def({ id: 'thermal', group: 'Thermal', title: 'Junction temperature & heatsink',+ inputs: [+ { key: 'mode', label: 'Solve for', type: 'select', options: ['junction temperature', 'required heatsink'], def: 'junction temperature' },+ { key: 'P', label: 'Power dissipated', unit: 'W', def: '5' },+ { key: 'Ta', label: 'Ambient', unit: '°C', def: '40', si: false },+ { key: 'jc', label: 'θJC', unit: '°C/W', def: '1.5', si: false },+ { key: 'cs', label: 'θCS (interface)', unit: '°C/W', def: '0.5', si: false },+ { key: 'sa', label: 'θSA (heatsink)', unit: '°C/W', def: '8', si: false, show: 'junction temperature' },+ { key: 'Tj', label: 'Max junction', unit: '°C', def: '125', si: false, show: 'required heatsink' }],+ formula: 'Tj = Ta + P·(θJC + θCS + θSA)', ref: 'Series thermal resistance model',+ compute(v) {+ if (v.mode === 'required heatsink') {+ const sa = (v.Tj - v.Ta) / v.P - v.jc - v.cs;+ return { outputs: [out('Heatsink θSA must be ≤', sa, '°C/W', { fmt: 'n', dp: 2, highlight: true })], warnings: sa <= 0 ? ['Not achievable: the junction-to-sink path alone exceeds the budget.'] : [] };+ }+ const Tj = v.Ta + v.P * (v.jc + v.cs + v.sa);+ return { outputs: [out('Junction temperature', Tj, '°C', { fmt: 'n', dp: 1, highlight: true }), out('Case temperature', v.Ta + v.P * (v.cs + v.sa), '°C', { fmt: 'n', dp: 1 }),+ out('Heatsink temperature', v.Ta + v.P * v.sa, '°C', { fmt: 'n', dp: 1 })] };+ } });++ def({ id: 'wire', group: 'Wiring', title: 'Wire gauge: resistance & drop',+ inputs: [+ { key: 'awg', label: 'Gauge (AWG; 0 = 1/0, −1 = 2/0 …)', unit: 'AWG', def: '24', si: false },+ { key: 'len', label: 'Cable length (one way)', unit: 'm', def: '1', si: false },+ { key: 'I', label: 'Current', unit: 'A', def: '1' },+ { key: 'rt', label: 'Count return conductor', type: 'select', options: ['yes', 'no'], def: 'yes' },+ { key: 'T', label: 'Conductor temperature', unit: '°C', def: '20', si: false }],+ formula: 'd = 0.127 mm · 92^((36 − AWG)/39), R = ρ(T)·L/A', ref: 'ASTM B258 gauge definition; annealed copper ρ = 1.724e-8 Ω·m',+ compute(v) {+ const d = 0.127 * Math.pow(92, (36 - v.awg) / 39), A = PI * (d / 2) ** 2 * 1e-6, rho = RHO_CU * (1 + ALPHA_CU * (v.T - 20));+ const Rm = rho / A, L = v.len * (v.rt === 'yes' ? 2 : 1), R = Rm * L;+ return { outputs: [out('Diameter', d, 'mm', { fmt: 'n', dp: 3 }), out('Area', A * 1e6, 'mm²', { fmt: 'n', dp: 4 }), out('Resistance per metre', Rm, 'Ω/m'),+ out('Loop resistance', R, 'Ω'), out('Voltage drop', R * v.I, 'V', { highlight: true }), out('Power lost', v.I * v.I * R, 'W')],+ notes: ['Solid-conductor figures; stranded wire of the same gauge is a few percent higher. Ampacity depends on insulation and bundling.'] };+ } });++ def({ id: 'rf', group: 'RF', title: 'dBm · watts · volts',+ inputs: [+ { key: 'val', label: 'Value', unit: '', def: '0', si: true },+ { key: 'unit', label: 'Unit', type: 'select', options: ['dBm', 'W', 'Vrms', 'Vpp'], def: 'dBm' },+ { key: 'Z', label: 'System impedance', unit: 'Ω', def: '50' }],+ formula: 'P = 10^((dBm − 30)/10) W, Vrms = √(P·Z), Vpp = 2√2·Vrms', ref: 'Sinusoid into a resistive load',+ compute(v) {+ let P;+ if (v.unit === 'dBm') P = Math.pow(10, (v.val - 30) / 10); else if (v.unit === 'W') P = v.val;+ else if (v.unit === 'Vrms') P = v.val * v.val / v.Z; else P = (v.val / (2 * Math.SQRT2)) ** 2 / v.Z;+ const Vr = Math.sqrt(P * v.Z);+ return { outputs: [out('Power', 10 * Math.log10(P) + 30, 'dBm', { fmt: 'n', dp: 2, highlight: true }), out('Power', P, 'W'), out('dBW', 10 * Math.log10(P), 'dBW', { fmt: 'n', dp: 2 }),+ out('RMS voltage', Vr, 'V'), out('Peak-to-peak voltage', Vr * 2 * Math.SQRT2, 'V'), out('dBµV', 20 * Math.log10(Vr / 1e-6), 'dBµV', { fmt: 'n', dp: 1 })] };+ } });++ def({ id: 'wavelength', group: 'RF', title: 'Wavelength & antenna lengths',+ inputs: [+ { key: 'f', label: 'Frequency', unit: 'Hz', def: '2.4G' },+ { key: 'er', label: 'Effective εr (1 = free space)', unit: '', def: '1', si: false }],+ formula: 'λ = c / (f·√εr)', ref: 'c = 299 792 458 m/s',+ compute(v) {+ const lam = 299792458 / (v.f * Math.sqrt(v.er));+ return { outputs: [out('Wavelength λ', lam * 1000, 'mm', { fmt: 'n', dp: 2, highlight: true }), out('λ/2', lam * 500, 'mm', { fmt: 'n', dp: 2 }), out('λ/4', lam * 250, 'mm', { fmt: 'n', dp: 2 }),+ out('λ/10 (lumped-element limit)', lam * 100, 'mm', { fmt: 'n', dp: 2 }), out('Delay per mm', Math.sqrt(v.er) / 299792458 * 1e-3, 's')],+ notes: ['Real dipoles are cut ~5 % shorter than λ/2 (end effect); tune on the bench.'] };+ } });++ def({ id: 'eseries', group: 'Components', title: 'Standard values & resistor codes',+ inputs: [+ { key: 'val', label: 'Wanted value', unit: 'Ω', def: '4k75' },+ { key: 'series', label: 'E-series', type: 'select', options: ['E6', 'E12', 'E24', 'E48', 'E96', 'E192'], def: 'E96', setting: 'e_series' }],+ formula: 'IEC 60063 preferred numbers; IEC 60062 colour code; EIA-96 SMD code', ref: 'IEC 60063 / 60062, EIA-96',+ compute(v) {+ const n = eNearest(v.val, v.series), sig = ['E48', 'E96', 'E192'].includes(v.series) ? 3 : 2;+ const o = [out('Nearest', n.nearest, 'Ω', { highlight: true }), out('Next below', n.below, 'Ω'), out('Next above', n.above, 'Ω'),+ out('Error of nearest', (n.nearest - v.val) / v.val * 100, '%', { fmt: 'n', dp: 2 }), out('Tolerance class', TOL[v.series], '', { fmt: 'raw' }),+ out('Colour bands', colourBands(n.nearest, sig).join(' · '), '', { fmt: 'raw' })];+ o.push(sig === 3 ? out('EIA-96 SMD code', eia96(n.nearest) || '— (not an E96 value)', '', { fmt: 'raw' }) : out('3-digit SMD code', smd3(n.nearest), '', { fmt: 'raw' }));+ return { outputs: o };+ } });+++ // ================================================================ expansion 2026-09-25+ const IN = 0.0254, MU0 = 4e-7 * PI, C0 = 299792458;+ const Z0ms = (w, h, t, er) => 87 / Math.sqrt(er + 1.41) * Math.log(5.98 * h / (0.8 * w + t));+ const Z0sl = (w, b, t, er) => 60 / Math.sqrt(er) * Math.log(1.9 * b / (0.8 * w + t));++ def({ id: 'spacing', group: 'PCB', title: 'Conductor spacing for voltage (IPC-2221 Table 6-1)',+ blurb: 'Minimum electrical clearance between conductors at sea level to 3050 m.',+ inputs: [+ { key: 'V', label: 'Peak voltage between conductors (DC or AC peak)', unit: 'V', def: '48' },+ { key: 'col', label: 'Conductor location', type: 'select', options: ['B1 internal layer', 'B2 external, uncoated (sea level – 3050 m)', 'B4 external, with permanent polymer coating / solder mask'], def: 'B2 external, uncoated (sea level – 3050 m)' }],+ formula: 'Table lookup up to 500 V; above 500 V: 500 V value + (V − 500) × per-volt increment', ref: 'IPC-2221B Table 6-1 (columns unchanged at sea level in IPC-2221C, Dec 2023); verified against two independent reproductions',+ compute(v) {+ const rows = [[15, .05, .1, .05], [30, .05, .1, .05], [50, .1, .6, .13], [100, .1, .6, .13], [150, .2, .6, .4], [170, .2, 1.25, .4], [250, .2, 1.25, .4], [300, .2, 1.25, .4], [500, .25, 2.5, .8]];+ const inc = [0.0025, 0.005, 0.00305], c = v.col.startsWith('B1') ? 0 : v.col.startsWith('B2') ? 1 : 2;+ if (!(v.V >= 0)) return { error: 'Enter a voltage.' };+ const d = v.V <= 500 ? rows.find(r => v.V <= r[0])[c + 1] : rows[8][c + 1] + (v.V - 500) * inc[c];+ return { outputs: [out('Minimum spacing', d, 'mm', { fmt: 'n', dp: 3, highlight: true }), out('Minimum spacing', d / IN, 'mil', { fmt: 'n', dp: 1 })],+ notes: ['IPC-2221C adds a B5 column, altitude categories and explicit solder-mask wording; columns A5–A7 (component leads, conformal coating) are not included here. Safety standards (IEC 62368-1, IEC 60664-1, UL) usually demand MORE creepage and clearance than IPC-2221 for mains and user-accessible circuits: they govern where they apply.'] };+ } });++ def({ id: 'diffpair', group: 'PCB', title: 'Differential pair impedance (edge-coupled)',+ inputs: [+ { key: 'geom', label: 'Geometry', type: 'select', options: ['microstrip', 'stripline'], def: 'microstrip' },+ { key: 'w', label: 'Trace width', unit: 'mm', def: '0.15', si: false },+ { key: 's', label: 'Edge-to-edge gap', unit: 'mm', def: '0.15', si: false },+ { key: 'h', label: 'Dielectric height (stripline: plane-to-plane b)', unit: 'mm', def: '0.1', si: false },+ { key: 'oz', label: 'Copper weight', unit: 'oz', def: '0.5', si: false },+ { key: 'er', label: 'εr', unit: '', def: '4.3', si: false }],+ formula: 'Microstrip: Zdiff = 2·Z0·(1 − 0.48·e^(−0.96·s/h)) · Stripline: Zdiff = 2·Z0·(1 − 0.347·e^(−2.9·s/b))', ref: 'IPC-2141A / National Semiconductor AN-905 closed forms (±10 %; confirm with your fab\'s field solver)',+ compute(v) {+ const t = v.oz * OZ_UM / 1000, ms = v.geom === 'microstrip';+ const Z0 = ms ? Z0ms(v.w, v.h, t, v.er) : Z0sl(v.w, v.h, t, v.er);+ const Zd = ms ? 2 * Z0 * (1 - 0.48 * Math.exp(-0.96 * v.s / v.h)) : 2 * Z0 * (1 - 0.347 * Math.exp(-2.9 * v.s / v.h));+ return { outputs: [out('Differential impedance', Zd, 'Ω', { fmt: 'n', dp: 1, highlight: true }), out('Odd-mode impedance', Zd / 2, 'Ω', { fmt: 'n', dp: 1 }),+ out('Single-ended Z0 (uncoupled)', Z0, 'Ω', { fmt: 'n', dp: 1 }), out('Gap / height', v.s / v.h, '', { fmt: 'n', dp: 2 })],+ notes: ['Common targets: USB 90 Ω, Ethernet / LVDS / PCIe / HDMI 100 Ω (PCIe Gen3+ 85 Ω).'] };+ } });++ def({ id: 'via', group: 'PCB', title: 'Via: resistance, current, parasitics',+ inputs: [+ { key: 'd', label: 'Finished hole diameter', unit: 'mm', def: '0.3', si: false },+ { key: 'tp', label: 'Barrel plating thickness', unit: 'µm', def: '25', si: false },+ { key: 'h', label: 'Via length (board thickness)', unit: 'mm', def: '1.6', si: false },+ { key: 'pad', label: 'Pad diameter', unit: 'mm', def: '0.6', si: false },+ { key: 'anti', label: 'Antipad (plane clearance) diameter', unit: 'mm', def: '1.0', si: false },+ { key: 'er', label: 'εr', unit: '', def: '4.3', si: false },+ { key: 'dT', label: 'Allowed temperature rise', unit: '°C', def: '10', si: false },+ { key: 'Z0', label: 'Line impedance (for rise-time degradation)', unit: 'Ω', def: '50' }],+ formula: 'A = π((d/2+t)² − (d/2)²), R = ρ·h/A, Imax: IPC-2221 external on A, L = 5.08·h·[ln(4h/d)+1] nH (h,d in in), C = 1.41·εr·T·D1/(D2 − D1) pF, Δt10-90 = 2.2·C·Z0/2',+ ref: 'Barrel geometry (as KiCad Via Size); L and C: H. Johnson & M. Graham, High-Speed Digital Design §7; thermal: k_Cu = 401 W/m·K',+ compute(v) {+ const r = v.d / 2, t = v.tp / 1000, A = PI * ((r + t) ** 2 - r ** 2), Amm2 = A;+ const R = RHO_CU * (v.h / 1000) / (Amm2 * 1e-6), Imax = 0.048 * Math.pow(v.dT, 0.44) * Math.pow(Amm2 / (IN * IN), 0.725);+ const hin = v.h / 25.4, din = v.d / 25.4, L = 5.08 * hin * (Math.log(4 * hin / din) + 1) * 1e-9;+ const C = v.anti > v.pad ? 1.41 * v.er * hin * (v.pad / 25.4) / ((v.anti - v.pad) / 25.4) * 1e-12 : NaN;+ return { outputs: [out('Barrel cross-section', Amm2, 'mm²', { fmt: 'n', dp: 4 }), out('DC resistance', R, 'Ω', { highlight: true }), out(`Current for ${v.dT} °C rise (IPC-2221 ext.)`, Imax, 'A'),+ out('Thermal resistance (barrel)', (v.h / 1000) / (401 * Amm2 * 1e-6), '°C/W', { fmt: 'n', dp: 1 }), out('Inductance', L, 'H'), out('Pad capacitance', C, 'F'),+ out('Via impedance √(L/C)', Math.sqrt(L / C), 'Ω', { fmt: 'n', dp: 1 }), out('10–90 % rise-time degradation', 2.2 * C * v.Z0 / 2, 's')],+ notes: ['IPC-2152 also covers vias (short vias carry more than the trace rule suggests); the IPC-2221 figure here is conservative. Use several vias in parallel for power.'] };+ } });++ def({ id: 'fusing', group: 'PCB', title: 'Fusing current (Onderdonk)',+ inputs: [+ { key: 'shape', label: 'Conductor', type: 'select', options: ['PCB trace', 'round wire'], def: 'PCB trace' },+ { key: 'w', label: 'Trace width', unit: 'mm', def: '0.25', si: false, show: 'PCB trace' },+ { key: 'oz', label: 'Copper weight', unit: 'oz', def: '1', si: false, show: 'PCB trace' },+ { key: 'dia', label: 'Wire diameter', unit: 'mm', def: '0.5', si: false, show: 'round wire' },+ { key: 't', label: 'Pulse duration', unit: 's', def: '1' },+ { key: 'Ta', label: 'Ambient', unit: '°C', def: '25', si: false }],+ formula: 'I = A·√( log10(1 + (Tm − Ta)/(234 + Ta)) / (33·t) ), A in circular mils, Tm = 1083 °C (copper)', ref: 'Onderdonk equation (adiabatic; used by Saturn PCB Toolkit)',+ compute(v) {+ const Amm2 = v.shape === 'PCB trace' ? v.w * v.oz * OZ_UM / 1000 : PI * (v.dia / 2) ** 2;+ const cmil = Amm2 / (IN * IN) * 4 / PI, I = cmil * Math.sqrt(Math.log10(1 + (1083 - v.Ta) / (234 + v.Ta)) / (33 * v.t));+ return { outputs: [out('Fusing current', I, 'A', { highlight: true }), out('Cross-section', Amm2, 'mm²', { fmt: 'n', dp: 4 }), out('Circular mils', cmil, 'cmil', { fmt: 'n', dp: 0 })],+ warnings: v.t > 10 ? ['Onderdonk assumes no heat loss: valid for short pulses (roughly < 10 s).'] : [],+ notes: ['This is where copper MELTS. Never design to it; use it to check that a fault clears a fuse before a trace opens.'] };+ } });++ def({ id: 'bandwidth', group: 'Signal', title: 'Rise time, bandwidth & critical length',+ inputs: [+ { key: 'tr', label: 'Signal rise time (10–90 %)', unit: 's', def: '1n' },+ { key: 'er', label: 'Effective εr of the line', unit: '', def: '3.3', si: false },+ { key: 'len', label: 'Trace length (for check)', unit: 'mm', def: '100', si: false }],+ formula: 'BW = 0.35/tr, f_knee = 0.5/tr, v = c/√εeff, critical length = tr·v/6', ref: 'H. Johnson, High-Speed Digital Design (1/6 rule of thumb)',+ compute(v) {+ const vel = C0 / Math.sqrt(v.er), lc = v.tr * vel / 6 * 1000, delay = v.len / 1000 / vel;+ return { outputs: [out('−3 dB bandwidth', 0.35 / v.tr, 'Hz'), out('Knee frequency', 0.5 / v.tr, 'Hz'), out('Propagation velocity', vel / C0 * 100, '% of c', { fmt: 'n', dp: 1 }),+ out('Delay per mm', 1e-3 / vel, 's'), out('Critical length (terminate beyond)', lc, 'mm', { fmt: 'n', dp: 1, highlight: true }), out('Delay of this trace', delay, 's'),+ out('This trace is', v.len > lc ? 'a transmission line: control impedance and terminate' : 'electrically short (lumped)', '', { fmt: 'raw' })] };+ } });++ def({ id: 'skin', group: 'Signal', title: 'Skin depth',+ inputs: [{ key: 'f', label: 'Frequency', unit: 'Hz', def: '100M' }, { key: 'mat', label: 'Conductor', type: 'select', options: ['copper', 'aluminium', 'gold', 'silver'], def: 'copper' }],+ formula: 'δ = √(2ρ / (ω·µ0·µr))', ref: 'Classical skin effect; ρ at 20 °C (Cu 1.724e-8, Al 2.65e-8, Au 2.44e-8, Ag 1.59e-8 Ω·m)',+ compute(v) {+ const rho = { copper: 1.724e-8, aluminium: 2.65e-8, gold: 2.44e-8, silver: 1.59e-8 }[v.mat], d = Math.sqrt(2 * rho / (2 * PI * v.f * MU0));+ return { outputs: [out('Skin depth', d * 1e6, 'µm', { fmt: 'n', dp: 2, highlight: true }), out('…in mil', d / IN * 1000, 'mil', { fmt: 'n', dp: 3 }),+ out('Copper weight equal to δ', d * 1e6 / OZ_UM, 'oz', { fmt: 'n', dp: 2 })] };+ } });++ def({ id: 'rlc', group: 'Signal', title: 'Reactance & RLC resonance',+ inputs: [+ { key: 'f', label: 'Frequency', unit: 'Hz', def: '1M' },+ { key: 'L', label: 'Inductance', unit: 'H', def: '10u' },+ { key: 'C', label: 'Capacitance', unit: 'F', def: '1n' },+ { key: 'R', label: 'Resistance', unit: 'Ω', def: '10' },+ { key: 'cfg', label: 'Configuration', type: 'select', options: ['series', 'parallel'], def: 'series' }],+ formula: 'XL = 2πfL, XC = 1/(2πfC), f0 = 1/(2π√LC), Q series = √(L/C)/R, Q parallel = R·√(C/L)', ref: 'Circuit theory',+ compute(v) {+ const w = 2 * PI * v.f, XL = w * v.L, XC = 1 / (w * v.C), f0 = 1 / (2 * PI * Math.sqrt(v.L * v.C));+ const Q = v.cfg === 'series' ? Math.sqrt(v.L / v.C) / v.R : v.R * Math.sqrt(v.C / v.L);+ let Z;+ if (v.cfg === 'series') Z = Math.hypot(v.R, XL - XC); else { const g = 1 / v.R, b = 1 / XC - 1 / XL; Z = 1 / Math.hypot(g, b); }+ return { outputs: [out('XL', XL, 'Ω'), out('XC', XC, 'Ω'), out('Resonant frequency', f0, 'Hz', { highlight: true }), out('Q', Q, '', { fmt: 'n', dp: 2 }),+ out('−3 dB bandwidth', f0 / Q, 'Hz'), out('|Z| at f', Z, 'Ω')] };+ } });++ def({ id: 'combine', group: 'Components', title: 'Series / parallel combinations',+ inputs: [+ { key: 'kind', label: 'Component', type: 'select', options: ['resistors', 'capacitors', 'inductors'], def: 'resistors' },+ { key: 'cfg', label: 'Connection', type: 'select', options: ['series', 'parallel'], def: 'parallel' },+ { key: 'list', label: 'Values (comma-separated, prefixes OK)', unit: '', def: '10k, 22k, 4k7', type: 'text' }],+ formula: 'R, L series: Σx · parallel: 1/Σ(1/x) · C: the reverse', ref: 'Circuit theory (inductors assume no mutual coupling)',+ compute(v) {+ const xs = String(v.list).split(/[,\s;]+/).filter(Boolean).map(x => parseNum(x)); if (!xs.length || xs.some(x => !(x > 0))) return { error: 'Enter positive values separated by commas.' };+ const sum = xs.reduce((a, b) => a + b, 0), rec = 1 / xs.reduce((a, b) => a + 1 / b, 0);+ const cap = v.kind === 'capacitors', val = (v.cfg === 'series') !== cap ? sum : rec;+ return { outputs: [out('Equivalent', val, v.kind === 'resistors' ? 'Ω' : cap ? 'F' : 'H', { highlight: true }), out('Parts', xs.length, '', { fmt: 'n', dp: 0 })] };+ } });++ def({ id: 'rfind', group: 'Components', title: 'Two-resistor combination finder',+ blurb: 'Hit an odd value with two standard resistors in series or parallel.',+ inputs: [+ { key: 'target', label: 'Target resistance', unit: 'Ω', def: '3k57' },+ { key: 'series', label: 'E-series', type: 'select', options: ['E6', 'E12', 'E24', 'E48', 'E96'], def: 'E24', setting: 'e_series' },+ { key: 'cfg', label: 'Allow', type: 'select', options: ['series or parallel', 'series only', 'parallel only'], def: 'series or parallel' }],+ formula: 'series: R = Ra + Rb, parallel: R = Ra·Rb/(Ra + Rb)', ref: 'Exhaustive search over the chosen E-series (as KiCad E-Series tool)',+ compute(v) {+ const T = v.target; if (!(T > 0)) return { error: 'Enter a target.' };+ const vals = eValuesInRange(T / 100, T * 100, v.series), rows = [];+ const single = eNearest(T, v.series).nearest;+ for (const a of vals) {+ if (v.cfg !== 'parallel only' && a < T) { const b = eNearest(T - a, v.series).nearest; if (b >= a) rows.push(['+', a, b, a + b]); }+ if (v.cfg !== 'series only' && a > T) { const bi = 1 / (1 / T - 1 / a); if (bi > 0) { const b = eNearest(bi, v.series).nearest; if (b >= a) rows.push(['‖', a, b, a * b / (a + b)]); } }+ }+ rows.sort((x, y) => Math.abs(x[3] - T) - Math.abs(y[3] - T));+ const top = rows.slice(0, 8); if (!top.length) return { error: 'No combination found.' };+ return { outputs: [out('Best combination', `${fmtSI(top[0][1], 'Ω')} ${top[0][0]} ${fmtSI(top[0][2], 'Ω')}`, '', { fmt: 'raw', highlight: true }), out('Gives', top[0][3], 'Ω'),+ out('Error', (top[0][3] - T) / T * 100, '%', { fmt: 'n', dp: 3 }), out(`Single ${v.series} nearest`, single, 'Ω'), out('Single-part error', (single - T) / T * 100, '%', { fmt: 'n', dp: 2 })],+ table: { head: ['Ra', '', 'Rb', 'Result', 'Error'], rows: top.map(r => [fmtSI(r[1], 'Ω'), r[0], fmtSI(r[2], 'Ω'), fmtSI(r[3], 'Ω', 5), fmtN((r[3] - T) / T * 100, '%', 3)]) } };+ } });++ def({ id: 'attenuator', group: 'RF', title: 'Resistive attenuator (Pi / Tee)',+ inputs: [{ key: 'dB', label: 'Attenuation', unit: 'dB', def: '6', si: false }, { key: 'Z', label: 'Impedance (in = out)', unit: 'Ω', def: '50' },+ { key: 'series', label: 'Nearest', type: 'select', options: ['E24', 'E96', 'E192'], def: 'E96' }],+ formula: 'K = 10^(dB/20) · Pi: Rshunt = Z(K+1)/(K−1), Rseries = Z(K²−1)/(2K) · Tee: Rseries = Z(K−1)/(K+1), Rshunt = 2ZK/(K²−1)', ref: 'Matched symmetric pads (as KiCad RF-Attenuators, Digi-Key attenuator calculator)',+ compute(v) {+ const K = Math.pow(10, v.dB / 20), Z = v.Z; if (!(K > 1)) return { error: 'Attenuation must be > 0 dB.' };+ const pS = Z * (K + 1) / (K - 1), pR = Z * (K * K - 1) / (2 * K), tR = Z * (K - 1) / (K + 1), tS = 2 * Z * K / (K * K - 1), n = x => eNearest(x, v.series).nearest;+ return { outputs: [out('Pi: shunt resistors (×2)', pS, 'Ω', { highlight: true }), out('Pi: series resistor', pR, 'Ω', { highlight: true }), out('Tee: series resistors (×2)', tR, 'Ω'), out('Tee: shunt resistor', tS, 'Ω')],+ table: { head: ['Part', 'Exact', `Nearest ${v.series}`], rows: [['Pi shunt', fmtSI(pS, 'Ω'), fmtSI(n(pS), 'Ω')], ['Pi series', fmtSI(pR, 'Ω'), fmtSI(n(pR), 'Ω')], ['Tee series', fmtSI(tR, 'Ω'), fmtSI(n(tR), 'Ω')], ['Tee shunt', fmtSI(tS, 'Ω'), fmtSI(n(tS), 'Ω')]] } };+ } });++ def({ id: 'vswr', group: 'RF', title: 'VSWR · return loss · mismatch loss',+ inputs: [{ key: 'val', label: 'Value', unit: '', def: '1.5', si: false }, { key: 'kind', label: 'Value is', type: 'select', options: ['VSWR', 'return loss (dB)', '|Γ|', 'load resistance (Ω)'], def: 'VSWR' },+ { key: 'Z0', label: 'System impedance', unit: 'Ω', def: '50' }],+ formula: '|Γ| = (VSWR−1)/(VSWR+1) = 10^(−RL/20) = |ZL−Z0|/(ZL+Z0), RL = −20·log|Γ|, ML = −10·log(1−|Γ|²)', ref: 'Transmission-line theory (resistive load)',+ compute(v) {+ let G;+ if (v.kind === 'VSWR') G = (v.val - 1) / (v.val + 1); else if (v.kind.startsWith('return')) G = Math.pow(10, -v.val / 20);+ else if (v.kind === '|Γ|') G = v.val; else G = Math.abs(v.val - v.Z0) / (v.val + v.Z0);+ if (!(G >= 0 && G < 1)) return { error: 'Out of range.' };+ return { outputs: [out('VSWR', (1 + G) / (1 - G), ':1', { fmt: 'n', dp: 3, highlight: true }), out('|Γ|', G, '', { fmt: 'n', dp: 4 }), out('Return loss', -20 * Math.log10(G), 'dB', { fmt: 'n', dp: 2 }),+ out('Mismatch loss', -10 * Math.log10(1 - G * G), 'dB', { fmt: 'n', dp: 3 }), out('Power reflected', G * G * 100, '%', { fmt: 'n', dp: 2 })] };+ } });++ def({ id: 'regulator', group: 'Power', title: 'Adjustable regulator feedback resistors',+ inputs: [+ { key: 'mode', label: 'Solve for', type: 'select', options: ['R2 for target Vout', 'Vout from resistors'], def: 'R2 for target Vout' },+ { key: 'Vref', label: 'Reference / feedback voltage', unit: 'V', def: '1.25' },+ { key: 'Iadj', label: 'ADJ/FB pin current (0 for most switchers)', unit: 'A', def: '50u' },+ { key: 'R1', label: 'R1 (between OUT and ADJ/FB → ground side: see note)', unit: 'Ω', def: '240' },+ { key: 'Vout', label: 'Target output', unit: 'V', def: '5', show: 'R2 for target Vout' },+ { key: 'R2', label: 'R2 (ADJ/FB to ground)', unit: 'Ω', def: '750', show: 'Vout from resistors' },+ { key: 'series', label: 'E-series', type: 'select', options: ['E24', 'E96'], def: 'E96' }],+ formula: 'Vout = Vref·(1 + R2/R1) + Iadj·R2', ref: 'TI LM317 datasheet (Vref 1.25 V, Iadj 50 µA typ); same form for switcher FB dividers with Iadj ≈ 0',+ compute(v) {+ const vo = R2 => v.Vref * (1 + R2 / v.R1) + v.Iadj * R2;+ if (v.mode.startsWith('R2')) {+ const R2 = (v.Vout - v.Vref) / (v.Vref / v.R1 + v.Iadj); if (!(R2 > 0)) return { error: 'Target must exceed Vref.' };+ const R2n = eNearest(R2, v.series).nearest;+ return { outputs: [out('Exact R2', R2, 'Ω'), out(`Nearest ${v.series}`, R2n, 'Ω', { highlight: true }), out('Resulting Vout', vo(R2n), 'V'), out('Error', (vo(R2n) - v.Vout) / v.Vout * 100, '%', { fmt: 'n', dp: 2 }), out('Divider current', v.Vref / v.R1, 'A')],+ notes: ['R1 sits between OUT and ADJ/FB, R2 between ADJ/FB and ground (LM317 naming). LM317 needs ≥ ~5 mA minimum load: R1 = 240 Ω gives 5.2 mA.'] };+ }+ return { outputs: [out('Output voltage', vo(v.R2), 'V', { highlight: true }), out('Divider current', v.Vref / v.R1, 'A')] };+ } });++ def({ id: 'mosfet', group: 'Power', title: 'MOSFET conduction & switching loss',+ inputs: [+ { key: 'V', label: 'Switched (off-state) voltage', unit: 'V', def: '24' },+ { key: 'I', label: 'Drain current (on)', unit: 'A', def: '5' },+ { key: 'Rds', label: 'Rds(on) at 25 °C', unit: 'Ω', def: '10m' },+ { key: 'kT', label: 'Rds(on) hot multiplier (datasheet, e.g. 1.5)', unit: '×', def: '1.5', si: false },+ { key: 'D', label: 'On duty cycle', unit: '%', def: '50', si: false },+ { key: 'fsw', label: 'Switching frequency (0 = static)', unit: 'Hz', def: '100k' },+ { key: 'tr', label: 'Rise time', unit: 's', def: '20n' },+ { key: 'tf', label: 'Fall time', unit: 's', def: '20n' },+ { key: 'Qg', label: 'Total gate charge', unit: 'C', def: '30n', si: true },+ { key: 'Vgs', label: 'Gate drive voltage', unit: 'V', def: '10' }],+ formula: 'Pcond = I²·Rds·k·D, Psw ≈ ½·V·I·(tr+tf)·fsw, Pgate = Qg·Vgs·fsw (in the driver)', ref: 'First-order hard-switching estimate (e.g. Infineon/TI MOSFET loss app notes)',+ compute(v) {+ const Pc = v.I * v.I * v.Rds * v.kT * v.D / 100, Ps = 0.5 * v.V * v.I * (v.tr + v.tf) * v.fsw, Pg = v.Qg * v.Vgs * v.fsw;+ return { outputs: [out('Conduction loss', Pc, 'W'), out('Switching loss', Ps, 'W'), out('Total in the MOSFET', Pc + Ps, 'W', { highlight: true }), out('Gate-drive power (driver)', Pg, 'W'), out('Average gate current', v.Qg * v.fsw, 'A')],+ notes: ['Ignores reverse recovery, Coss and ringing losses; add margin at high frequency.'] };+ } });++ def({ id: 'pdn', group: 'Power', title: 'PDN target impedance',+ inputs: [{ key: 'V', label: 'Rail voltage', unit: 'V', def: '1.0' }, { key: 'rip', label: 'Allowed ripple', unit: '%', def: '3', si: false }, { key: 'dI', label: 'Transient current step', unit: 'A', def: '5' },+ { key: 'fmax', label: 'Highest frequency of concern', unit: 'Hz', def: '100M' }],+ formula: 'Z_target = V·ripple / ΔI', ref: 'L. D. Smith et al., "Power Distribution System Design Methodology" (target-impedance method)',+ compute(v) {+ const Z = v.V * v.rip / 100 / v.dI;+ return { outputs: [out('Target impedance', Z, 'Ω', { highlight: true }), out('Max ESL per decap at fmax', Z / (2 * PI * v.fmax), 'H')], notes: ['Keep |Z| below the target from DC to fmax with VRM + bulk + ceramics + plane capacitance.'] };+ } });++ def({ id: 'opamp', group: 'Signal', title: 'Op-amp gain & bandwidth',+ inputs: [+ { key: 'cfg', label: 'Configuration', type: 'select', options: ['non-inverting', 'inverting'], def: 'non-inverting' },+ { key: 'Rf', label: 'Feedback resistor Rf', unit: 'Ω', def: '10k' },+ { key: 'Rg', label: 'Gain / input resistor Rg', unit: 'Ω', def: '1k' },+ { key: 'gbw', label: 'Gain-bandwidth product', unit: 'Hz', def: '10M' },+ { key: 'sr', label: 'Slew rate', unit: 'V/s', def: '10M' },+ { key: 'Vpk', label: 'Output amplitude (peak)', unit: 'V', def: '2' }],+ formula: 'non-inv: G = 1 + Rf/Rg · inv: G = −Rf/Rg · f−3dB = GBW/(1 + Rf/Rg) · full-power BW = SR/(2π·Vpk)', ref: 'Voltage-feedback op-amp, single-pole model',+ compute(v) {+ const ng = 1 + v.Rf / v.Rg, G = v.cfg === 'inverting' ? -v.Rf / v.Rg : ng;+ return { outputs: [out('Gain', G, 'V/V', { fmt: 'n', dp: 3, highlight: true }), out('Gain', 20 * Math.log10(Math.abs(G)), 'dB', { fmt: 'n', dp: 2 }), out('Noise gain', ng, 'V/V', { fmt: 'n', dp: 3 }),+ out('Small-signal −3 dB bandwidth', v.gbw / ng, 'Hz'), out('Full-power bandwidth', v.sr / (2 * PI * v.Vpk), 'Hz'), out('Input impedance', v.cfg === 'inverting' ? v.Rg : Infinity, 'Ω')] };+ } });++ def({ id: 'timer555', group: 'Signal', title: '555 timer',+ inputs: [+ { key: 'mode', label: 'Mode', type: 'select', options: ['astable', 'monostable'], def: 'astable' },+ { key: 'RA', label: 'RA', unit: 'Ω', def: '1k', show: 'astable' }, { key: 'RB', label: 'RB', unit: 'Ω', def: '10k', show: 'astable' },+ { key: 'R', label: 'R', unit: 'Ω', def: '100k', show: 'monostable' }, { key: 'C', label: 'C', unit: 'F', def: '10n' }],+ formula: 'astable: f = 1.44/((RA+2RB)·C), tH = 0.693(RA+RB)C, tL = 0.693·RB·C · monostable: t = 1.1·R·C', ref: 'TI NE555 datasheet (SLFS022)',+ compute(v) {+ if (v.mode === 'monostable') return { outputs: [out('Pulse width', 1.1 * v.R * v.C, 's', { highlight: true })] };+ const tH = 0.693 * (v.RA + v.RB) * v.C, tL = 0.693 * v.RB * v.C;+ return { outputs: [out('Frequency', 1.44 / ((v.RA + 2 * v.RB) * v.C), 'Hz', { highlight: true }), out('High time', tH, 's'), out('Low time', tL, 's'), out('Duty cycle', tH / (tH + tL) * 100, '%', { fmt: 'n', dp: 1 })] };+ } });++ def({ id: 'ntc', group: 'Measurement', title: 'NTC thermistor (β model)',+ inputs: [+ { key: 'mode', label: 'Solve for', type: 'select', options: ['resistance at temperature', 'temperature from resistance'], def: 'resistance at temperature' },+ { key: 'R25', label: 'R at 25 °C', unit: 'Ω', def: '10k' }, { key: 'B', label: 'β (B25/85)', unit: 'K', def: '3435', si: false },+ { key: 'T', label: 'Temperature', unit: '°C', def: '60', si: false, show: 'resistance at temperature' },+ { key: 'R', label: 'Measured resistance', unit: 'Ω', def: '3k', show: 'temperature from resistance' },+ { key: 'Rp', label: 'Pull-up to Vcc (divider, optional)', unit: 'Ω', def: '10k' }, { key: 'Vcc', label: 'Divider supply', unit: 'V', def: '3.3' }],+ formula: 'R(T) = R25·exp(β·(1/T − 1/298.15)), 1/T = 1/298.15 + ln(R/R25)/β', ref: 'β-parameter model (±1 °C typical over 0–100 °C; Steinhart-Hart is tighter)',+ compute(v) {+ let R, T;+ if (v.mode.startsWith('resistance')) { T = v.T; R = v.R25 * Math.exp(v.B * (1 / (T + 273.15) - 1 / 298.15)); }+ else { R = v.R; T = 1 / (1 / 298.15 + Math.log(R / v.R25) / v.B) - 273.15; }+ const o = [out('Resistance', R, 'Ω', { highlight: v.mode.startsWith('resistance') }), out('Temperature', T, '°C', { fmt: 'n', dp: 2, highlight: !v.mode.startsWith('resistance') })];+ if (Number.isFinite(v.Rp)) o.push(out('Divider output (NTC to ground)', v.Vcc * R / (R + v.Rp), 'V'));+ return { outputs: o };+ } });++ def({ id: 'ppm', group: 'Interfaces', title: 'Frequency tolerance (ppm)',+ inputs: [{ key: 'f', label: 'Nominal frequency', unit: 'Hz', def: '32.768k' }, { key: 'ppm', label: 'Tolerance', unit: 'ppm', def: '20', si: false }, { key: 'meas', label: 'Measured frequency (optional)', unit: 'Hz', def: '' }],+ formula: 'Δf = f·ppm/10⁶, drift per day = 86400·ppm/10⁶ s', ref: 'Definition',+ compute(v) {+ const o = [out('Frequency error', v.f * v.ppm * 1e-6, 'Hz', { highlight: true }), out('Clock drift per day', 86400 * v.ppm * 1e-6, 's'), out('Clock drift per month', 30 * 86400 * v.ppm * 1e-6, 's')];+ if (Number.isFinite(v.meas)) o.push(out('Measured error', (v.meas - v.f) / v.f * 1e6, 'ppm', { fmt: 'n', dp: 2 }));+ return { outputs: o };+ } });++ def({ id: 'spiral', group: 'RF', title: 'Planar spiral inductor',+ inputs: [{ key: 'shape', label: 'Shape', type: 'select', options: ['square', 'hexagonal', 'octagonal'], def: 'square' }, { key: 'n', label: 'Turns', unit: '', def: '5', si: false },+ { key: 'dout', label: 'Outer diameter', unit: 'mm', def: '5', si: false }, { key: 'din', label: 'Inner diameter', unit: 'mm', def: '2', si: false }],+ formula: 'L = K1·µ0·n²·d_avg / (1 + K2·ρ), d_avg = (dout+din)/2, ρ = (dout−din)/(dout+din)', ref: 'Modified Wheeler: Mohan, Hershenson, Boyd & Lee, IEEE JSSC 34(10), 1999 (K1/K2: square 2.34/2.75, hex 2.33/3.82, oct 2.25/3.55)',+ compute(v) {+ const [K1, K2] = { square: [2.34, 2.75], hexagonal: [2.33, 3.82], octagonal: [2.25, 3.55] }[v.shape];+ const davg = (v.dout + v.din) / 2 / 1000, rho = (v.dout - v.din) / (v.dout + v.din); if (!(v.dout > v.din)) return { error: 'Outer diameter must exceed inner.' };+ return { outputs: [out('Inductance', K1 * MU0 * v.n * v.n * davg / (1 + K2 * rho), 'H', { highlight: true }), out('Fill ratio ρ', rho, '', { fmt: 'n', dp: 3 })], notes: ['About ±8 % against measurement in the paper; ignores a nearby ground plane, which lowers L.'] };+ } });++ def({ id: 'units', group: 'Components', title: 'Length & copper unit converter',+ inputs: [{ key: 'val', label: 'Value', unit: '', def: '10', si: false }, { key: 'u', label: 'Unit', type: 'select', options: ['mm', 'mil', 'inch', 'µm', 'oz copper'], def: 'mil' }],+ formula: '1 mil = 0.0254 mm, 1 oz/ft² Cu ≈ 34.8 µm (1.37 mil)', ref: 'Definitions',+ compute(v) {+ const mm = { mm: v.val, mil: v.val * IN, inch: v.val * 25.4, 'µm': v.val / 1000, 'oz copper': v.val * OZ_UM / 1000 }[v.u];+ return { outputs: [out('mm', mm, 'mm', { fmt: 'n', dp: 4 }), out('mil', mm / IN, 'mil', { fmt: 'n', dp: 3 }), out('inch', mm / 25.4, 'in', { fmt: 'n', dp: 5 }),+ out('µm', mm * 1000, 'µm', { fmt: 'n', dp: 2 }), out('as copper weight', mm * 1000 / OZ_UM, 'oz', { fmt: 'n', dp: 3 })] };+ } });++ // ---------------------------------------------------------------- driver+ function inputsFor(calc, raw = {}, settings = {}) {+ const v = {};+ for (const f of calc.inputs) {+ let r = raw[f.key];+ if (r === undefined) r = (f.setting && settings[f.setting] !== undefined && f.type === 'select' && f.options.includes(settings[f.setting])) ? settings[f.setting]+ : (f.setting && settings[f.setting] !== undefined ? String(settings[f.setting]) : f.def);+ v[f.key] = (f.type === 'select' || f.type === 'text') ? String(r) : parseNum(r, f.si !== false);+ }+ return v;+ }+ function visible(field, v) {+ if (!field.show) return true;+ const s = Array.isArray(field.show) ? field.show : [field.show];+ return Object.values(v).some(x => s.includes(x));+ }+ function run(id, raw = {}, settings = {}) {+ const calc = CALCS.find(c => c.id === id);+ if (!calc) return { ok: false, error: `Unknown calculator "${id}".`, known: CALCS.map(c => c.id) };+ const v = inputsFor(calc, raw, settings);+ let res;+ try { res = calc.compute(v) || {}; } catch (e) { res = { error: String(e.message || e) }; }+ const outputs = (res.outputs || []).map(o => ({ ...o, text: o.fmt === 'raw' ? String(o.value) : o.fmt === 'n' ? fmtN(o.value, o.unit, o.dp ?? 3) : fmtSI(o.value, o.unit) }));+ return { ok: !res.error, calc: id, title: calc.title, inputs: v, error: res.error, outputs, table: res.table, notes: res.notes || [], warnings: res.warnings || [], formula: calc.formula, ref: calc.ref };+ }+ function catalog() {+ return CALCS.map(c => ({ id: c.id, group: c.group, title: c.title, blurb: c.blurb || '', formula: c.formula, ref: c.ref,+ inputs: c.inputs.map(f => ({ key: f.key, label: f.label, unit: f.unit || '', type: f.type || 'number', options: f.options, def: f.def, show: f.show, si: f.si !== false, setting: f.setting })) }));+ }++ return { CALCS, run, catalog, parseNum, fmtSI, fmtN, eNearest, eValuesInRange, E_BASE, colourBands, eia96, visible, inputsFor };+});
docs/hero.pngadded⋯ 1 unchanged line ⋯
install.shadded+13@@ -0,0 +1,13 @@+#!/bin/bash+# install.sh for hardware-calculator (app): links the hwcalc CLI and installs the user skill. Runs from the module dir.+set -euo pipefail+DIR="$(cd "$(dirname "$0")" && pwd)"+command -v node >/dev/null || { echo "hwcalc needs Node.js 18+ on PATH" >&2; exit 1; }+BIN_DIR="${HOME}/.local/bin"; mkdir -p "$BIN_DIR"+chmod 0755 "$DIR/bin/hwcalc"+ln -sfn "$DIR/bin/hwcalc" "$BIN_DIR/hwcalc" # a link, not a copy: the CLI loads calcs.js/server.js beside it+echo "Linked hwcalc -> $BIN_DIR/hwcalc"+mkdir -p "${HOME}/.claude/skills/hwcalc"+install -m 0644 "$DIR/skills/hwcalc/SKILL.md" "${HOME}/.claude/skills/hwcalc/SKILL.md"+echo "Installed skill -> ~/.claude/skills/hwcalc/SKILL.md"+echo "Hardware Calculator installed. Try: hwcalc --ai-thread \"<name>\" start or hwcalc calc crystal CL=12p Cs=4p"
package.jsonadded+100@@ -0,0 +1,100 @@+{+ "slug": "hardware-calculator",+ "title": "Hardware Calculator",+ "name": "hardware-calculator",+ "version": "0.3.0",+ "type": "app",+ "description": "40 hardware design calculators whose every number traces to a standard (IPC-2152/2221C/2141, ST AN2867, NXP UM10204, IEC 60063), with live labelled schematics and PCB cross-sections. Hydrogen UI, CLI and HTTP API.",+ "dependencies": {},+ "bin": {+ "hwcalc": "bin/hwcalc"+ },+ "tags": [+ "calculator",+ "pcb",+ "ipc-2152",+ "ipc-2221",+ "impedance",+ "crystal",+ "oscillator",+ "power",+ "rf",+ "electronics",+ "schematic",+ "mit"+ ],+ "license": "MIT",+ "needs_sudo": false,+ "scripts": {+ "install": "./install.sh",+ "uninstall": "./uninstall.sh",+ "test": "node test.js",+ "start": "node server.js --port auto"+ },+ "files": [+ "bin/**",+ "public/**",+ "skills/**",+ "calcs.js",+ "schematics.js",+ "server.js",+ "test.js",+ "install.sh",+ "uninstall.sh",+ "package.json",+ "README.md",+ "SOURCES.md",+ "CHANGELOG.md",+ "docs/hero.png"+ ],+ "changelog": "0.3.0: AN2867-verified crystal oscillator CL calculator; live schematics for 26 calculators; sources register",+ "discovery_triggers": [+ "hardware calculator",+ "hwcalc",+ "trace width",+ "trace current",+ "IPC-2152",+ "IPC-2221",+ "clearance for voltage",+ "creepage clearance PCB",+ "microstrip impedance",+ "stripline impedance",+ "differential pair impedance",+ "via current",+ "crystal load capacitors",+ "oscillator capacitors",+ "gain margin crystal",+ "voltage divider",+ "LED resistor",+ "I2C pull-up",+ "buck inductor",+ "boost inductor",+ "LM317 resistors",+ "attenuator",+ "VSWR",+ "junction temperature",+ "E-series value"+ ],+ "discovery_pitch": "40 standards-verified hardware calculators (IPC trace width, spacing, impedance, crystal CL, power, RF) with live labelled schematics. Say 'with the hardware calculator' to your AI.",+ "sample_prompts": [+ {+ "label": "trace width for 3 A",+ "prompt": "with the hardware calculator, what trace width for 3 A at 20 °C rise on 2 oz copper?"+ },+ {+ "label": "crystal load caps + gain margin",+ "prompt": "size the load caps for a 12 pF crystal and check the gain margin with 25 mA/V gm"+ },+ {+ "label": "clearance for 300 V",+ "prompt": "hardware calculator: PCB clearance for 300 V on an external coated layer"+ },+ {+ "label": "buck 12 V → 3.3 V",+ "prompt": "open the hardware calculator on a buck from 12 V to 3.3 V at 2 A, 500 kHz"+ }+ ],+ "hero": {+ "path": "docs/hero.png"+ }+}
public/index.htmladded+214@@ -0,0 +1,214 @@+<!doctype html>+<html lang="en"><head>+<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">+<title>Hardware Calculator</title>+<style>+@font-face { font-family: 'Satoshi'; src: url('https://wiki.adom.inc/static/fonts/satoshi-400.woff2') format('woff2'); font-weight: 400; }+@font-face { font-family: 'Satoshi'; src: url('https://wiki.adom.inc/static/fonts/satoshi-500.woff2') format('woff2'); font-weight: 500; }+@font-face { font-family: 'Familjen Grotesk'; src: url('https://wiki.adom.inc/static/fonts/familjen-grotesk-700.woff2') format('woff2'); font-weight: 700; }+:root { --bg:#0d1117; --panel:#161b22; --panel2:#1c2330; --line:#262d38; --ink:#e6edf3; --dim:#8b949e; --teal:#00b8b0; --blue:#2f81f7; --warn:#f5a524; --err:#f85149; }+* { box-sizing: border-box; margin: 0; padding: 0; }+html, body { height: 100%; background: var(--bg); color: var(--ink); font: 14px/1.5 'Satoshi', -apple-system, 'Segoe UI', sans-serif; }+header { height: 44px; display: flex; align-items: center; gap: 12px; padding: 0 14px; border-bottom: 1px solid var(--line); background: var(--panel); }+header .logo { width: 22px; height: 22px; border-radius: 6px; background: linear-gradient(135deg, var(--teal), var(--blue)); display: grid; place-items: center; font: 700 12px 'Familjen Grotesk'; color: #04121a; }+header h1 { font: 700 15px 'Familjen Grotesk', sans-serif; letter-spacing: .01em; }+header .ver { color: var(--dim); font-size: 12px; }+header .sp { flex: 1; }+.icon-btn { width: 30px; height: 30px; border-radius: 8px; border: 1px solid transparent; background: none; color: #fff; display: grid; place-items: center; cursor: pointer; position: relative; }+.icon-btn:hover { background: var(--panel2); border-color: var(--line); }+[data-tip]:hover::after { content: attr(data-tip); position: absolute; top: 36px; right: 0; white-space: nowrap; background: #0b0f14; border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; font-size: 12px; color: var(--ink); z-index: 50; transition-delay: .4s; }+.app { display: grid; grid-template-columns: 250px 1fr; height: calc(100% - 44px); }+nav { border-right: 1px solid var(--line); overflow: auto; padding: 10px 8px 20px; }+nav input { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; color: var(--ink); padding: 7px 10px; font: inherit; margin-bottom: 8px; }+nav input:focus { outline: none; border-color: var(--teal); }+nav .grp { font-size: 11px; letter-spacing: .06em; color: var(--dim); padding: 10px 8px 4px; }+nav .item { display: block; width: 100%; text-align: left; background: none; border: 0; color: #c9d1d9; padding: 6px 10px; border-radius: 7px; cursor: pointer; font: inherit; }+nav .item:hover { background: var(--panel2); }+nav .item.on { background: rgba(0,184,176,.14); color: var(--ink); box-shadow: inset 2px 0 0 var(--teal); }+main { overflow: auto; padding: 22px 28px 60px; }+.title h2 { font: 700 21px 'Familjen Grotesk', sans-serif; }+.title p { color: var(--dim); margin-top: 3px; }+.cols { display: grid; grid-template-columns: minmax(280px, 380px) 1fr; gap: 22px; margin-top: 18px; align-items: start; }+#pick { display: none; width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; color: var(--ink); padding: 8px 10px; font: 500 14px 'Satoshi', sans-serif; margin-bottom: 14px; }+@media (max-width: 900px) { .app { grid-template-columns: 1fr; } nav { display: none; } .cols { grid-template-columns: 1fr; } #pick { display: block; } }+.card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }+.stack { display: grid; gap: 22px; }+#schem svg { width: 100%; height: auto; display: block; }+.card h3 { font-size: 12px; letter-spacing: .06em; color: var(--dim); font-weight: 500; margin-bottom: 10px; }+.field { margin-bottom: 11px; }+.field label { display: block; font-size: 12.5px; color: #aeb8c4; margin-bottom: 4px; }+.field .row { display: flex; align-items: center; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }+.field .row:focus-within { border-color: var(--teal); }+.field input, .field select { flex: 1; min-width: 0; background: none; border: 0; color: var(--ink); padding: 8px 10px; font: 500 14px 'Satoshi', monospace; }+.field select { cursor: pointer; }+.field select option { background: var(--panel); }+.field input:focus, .field select:focus { outline: none; }+.field .unit { color: var(--dim); padding-right: 10px; font-size: 12.5px; white-space: nowrap; }+.field.bad .row { border-color: var(--err); }+.hint { font-size: 12px; color: var(--dim); margin-top: 6px; }+.res { display: grid; grid-template-columns: 1fr auto; gap: 0; }+.res > div { padding: 8px 2px; border-bottom: 1px solid var(--line); }+.res .l { color: #aeb8c4; }+.res .v { text-align: right; font: 500 14.5px 'Satoshi', monospace; font-variant-numeric: tabular-nums; cursor: copy; }+.res .v:hover { color: var(--teal); }+.res .hl { color: var(--teal); font-size: 17px; font-weight: 700; }+.msg { border-radius: 8px; padding: 9px 12px; margin-top: 12px; font-size: 13px; }+.msg.err { background: rgba(248,81,73,.1); border: 1px solid rgba(248,81,73,.35); color: #ffb4ae; }+.msg.warn { background: rgba(245,165,36,.08); border: 1px solid rgba(245,165,36,.3); color: #f3d9a7; }+.msg.note { background: rgba(47,129,247,.07); border: 1px solid rgba(47,129,247,.25); color: #c4d8f6; }+.formula { margin-top: 14px; padding-top: 12px; border-top: 1px dashed var(--line); font-size: 12.5px; color: var(--dim); }+.formula code { color: #d2dae4; font: 12.5px ui-monospace, Menlo, monospace; display: block; margin: 3px 0 5px; white-space: pre-wrap; }+table { width: 100%; border-collapse: collapse; margin-top: 14px; font-size: 13px; }+th { text-align: left; color: var(--dim); font-weight: 500; font-size: 11.5px; letter-spacing: .04em; border-bottom: 1px solid var(--line); padding: 6px; }+td { padding: 6px; border-bottom: 1px solid var(--line); font-variant-numeric: tabular-nums; }+tbody tr:first-child td { color: var(--teal); }+.btn { background: var(--panel2); border: 1px solid var(--line); color: var(--ink); border-radius: 8px; padding: 6px 11px; font: inherit; font-size: 12.5px; cursor: pointer; }+.btn:hover { border-color: var(--teal); }+.actions { display: flex; gap: 8px; margin-top: 12px; }+.modal { position: fixed; inset: 0; background: rgba(0,0,0,.55); display: none; align-items: flex-start; justify-content: center; padding-top: 70px; z-index: 40; }+.modal.on { display: flex; }+.modal .box { width: 460px; max-width: 94vw; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 18px; }+.modal h3 { font: 700 16px 'Familjen Grotesk', sans-serif; margin-bottom: 12px; display: flex; justify-content: space-between; }+.set { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 9px 0; border-bottom: 1px solid var(--line); }+.set span { color: #c9d1d9; font-size: 13px; }+.set select, .set input { background: var(--bg); border: 1px solid var(--line); color: var(--ink); border-radius: 7px; padding: 5px 8px; font: inherit; width: 110px; }+.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: #0b0f14; border: 1px solid var(--line); border-radius: 9px; padding: 8px 14px; font-size: 13px; opacity: 0; transition: opacity .2s; pointer-events: none; z-index: 60; }+.toast.on { opacity: 1; }+</style></head>+<body>+<header>+ <div class="logo">∑</div><h1>Hardware Calculator</h1><span class="ver" id="ver"></span><span class="sp"></span>+ <button class="icon-btn" id="gear" data-tip="Settings" aria-label="Settings">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>+ </button>+</header>+<div class="app">+ <nav><input id="q" placeholder="Search calculators…" autocomplete="off"><div id="list"></div></nav>+ <main>+ <select id="pick" aria-label="Calculator"></select><div class="title"><h2 id="t"></h2><p id="blurb"></p></div>+ <div class="cols">+ <div class="card"><h3>Inputs</h3><div id="form"></div>+ <div class="hint">Prefixes work: 4k7, 10u, 2.2M, 100n. Results update as you type.</div>+ <div class="actions"><button class="btn" id="reset">Reset to defaults</button></div></div>+ <div class="stack"><div class="card"><h3>Results</h3><div id="out"></div>+ <div class="actions"><button class="btn" id="copy">Copy results</button><button class="btn" id="link">Copy link</button></div></div><div class="card" id="schemCard" hidden><h3 id="schemH">Schematic</h3><div id="schem"></div></div></div>+ </div>+ </main>+</div>+<div class="modal" id="modal"><div class="box"><h3>Settings <button class="icon-btn" id="close" aria-label="Close">✕</button></h3><div id="sets"></div>+ <div class="hint" id="sver"></div></div></div>+<div class="toast" id="toast"></div>+<script src="calcs.js"></script>+<script src="schematics.js"></script>+<script>+const H = window.HWCALC, $ = s => document.querySelector(s);+const CAT = H.catalog();+let settings = {}, spec = {}, cur = 'divider', vals = {}, lastRes = null, usedHash = false, seenRev = 0;+const toast = m => { const t = $('#toast'); t.textContent = m; t.classList.add('on'); clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove('on'), 1600); };+const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++function renderPick() {+ const groups = [...new Set(CAT.map(c => c.group))];+ $('#pick').innerHTML = groups.map(g => `<optgroup label="${esc(g)}">` + CAT.filter(c => c.group === g).map(c => `<option value="${c.id}"${c.id === cur ? ' selected' : ''}>${esc(c.title)}</option>`).join('') + '</optgroup>').join('');+}+$('#pick').onchange = e => select(e.target.value);+function renderList() {+ const q = $('#q').value.trim().toLowerCase(); let html = '', grp = '';+ for (const c of CAT) {+ if (q && !(c.title + ' ' + c.group + ' ' + c.blurb + ' ' + c.formula).toLowerCase().includes(q)) continue;+ if (c.group !== grp) { grp = c.group; html += `<div class="grp">${esc(grp.toUpperCase())}</div>`; }+ html += `<button class="item${c.id === cur ? ' on' : ''}" data-id="${c.id}">${esc(c.title)}</button>`;+ }+ $('#list').innerHTML = html || '<div class="hint" style="padding:8px">No match.</div>';+}+$('#list').onclick = e => { const b = e.target.closest('.item'); if (b) select(b.dataset.id); };+$('#q').oninput = renderList;++function select(id, inputs) {+ cur = id; const c = CAT.find(x => x.id === id);+ vals = {}; for (const f of c.inputs) vals[f.key] = (inputs && inputs[f.key] !== undefined) ? String(inputs[f.key]) : defaultFor(f);+ $('#t').textContent = c.title; $('#blurb').textContent = c.blurb || '';+ renderList(); renderPick(); renderForm(); compute(); pushState();+}+function defaultFor(f) {+ if (f.setting && settings[f.setting] !== undefined) {+ if (f.type !== 'select' || f.options.includes(settings[f.setting])) return String(settings[f.setting]);+ }+ return f.def ?? '';+}+function visible(f) { if (!f.show) return true; const s = Array.isArray(f.show) ? f.show : [f.show]; return Object.values(vals).some(v => s.includes(v)); }+function renderForm() {+ const c = CAT.find(x => x.id === cur);+ $('#form').innerHTML = c.inputs.filter(visible).map(f => `<div class="field" data-k="${f.key}"><label>${esc(f.label)}</label><div class="row">` ++ (f.type === 'select' ? `<select data-k="${f.key}">${f.options.map(o => `<option${o === vals[f.key] ? ' selected' : ''}>${esc(o)}</option>`).join('')}</select>`+ : `<input data-k="${f.key}" value="${esc(vals[f.key] ?? '')}" ${f.type === 'text' ? '' : 'inputmode="decimal"'} spellcheck="false">`) ++ (f.unit ? `<span class="unit">${esc(f.unit)}</span>` : '') + `</div></div>`).join('');+}+$('#form').addEventListener('input', e => { const k = e.target.dataset.k; if (!k) return; vals[k] = e.target.value; if (e.target.tagName === 'SELECT') renderForm(); compute(); pushSoon(); });+$('#form').addEventListener('change', e => { if (e.target.tagName === 'SELECT') { vals[e.target.dataset.k] = e.target.value; renderForm(); compute(); pushSoon(); } });++function compute() {+ const c = CAT.find(x => x.id === cur);+ for (const f of c.inputs) { const el = document.querySelector(`.field[data-k="${f.key}"]`); if (!el || f.type === 'select' || f.type === 'text') continue;+ const s = vals[f.key]; el.classList.toggle('bad', s !== '' && s !== undefined && !Number.isFinite(H.parseNum(s, f.si))); }+ const r = H.run(cur, vals, settings); lastRes = r;+ try { history.replaceState(null, '', '#' + cur + '?' + new URLSearchParams(vals).toString()); } catch {}+ let h = '';+ if (r.error) h += `<div class="msg err">${esc(r.error)}</div>`;+ else h += `<div class="res">` + r.outputs.map(o => `<div class="l">${esc(o.label)}</div><div class="v${o.highlight ? ' hl' : ''}" title="Click to copy">${esc(o.text)}</div>`).join('') + `</div>`;+ if (r.table) h += `<table><thead><tr>${r.table.head.map(x => `<th>${esc(x)}</th>`).join('')}</tr></thead><tbody>${r.table.rows.map(row => `<tr>${row.map(x => `<td>${esc(x)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;+ for (const w of r.warnings) h += `<div class="msg warn">${esc(w)}</div>`;+ for (const n of r.notes) h += `<div class="msg note">${esc(n)}</div>`;+ if (settings.show_formulas !== false) h += `<div class="formula">Formula<code>${esc(r.formula)}</code>Reference: ${esc(r.ref)}</div>`;+ $('#out').innerHTML = h;+ const svg = settings.show_schematics !== false && window.HWSCHEM ? HWSCHEM.draw(cur, vals, settings) : null;+ $('#schemCard').hidden = !svg; if (svg) { $('#schem').innerHTML = svg; $('#schemH').textContent = cur === 'spiral' ? 'Layout' : /impedance|diffpair|trace|via|spacing/.test(cur) ? 'Cross-section' : 'Schematic'; }+}+$('#out').addEventListener('click', e => { if (e.target.classList.contains('v')) { navigator.clipboard?.writeText(e.target.textContent); toast('Copied ' + e.target.textContent); } });+$('#copy').onclick = () => {+ const r = lastRes; if (!r) return;+ const lines = [r.title, ...Object.entries(vals).map(([k, v]) => ` ${k} = ${v}`), ...(r.outputs || []).map(o => `${o.label}: ${o.text}`), `Formula: ${r.formula}`, `Ref: ${r.ref}`];+ navigator.clipboard?.writeText(lines.join('\n')); toast('Results copied');+};+$('#link').onclick = () => { navigator.clipboard?.writeText(location.href); toast('Link copied (opens this calculation with these inputs)'); };+$('#reset').onclick = () => { select(cur); toast('Defaults restored'); };++let pushT = null; const pushSoon = () => { clearTimeout(pushT); pushT = setTimeout(pushState, 500); };+function pushState() { fetch('ui/state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ calc: cur, inputs: vals }) }).catch(() => {}); }++// settings+function renderSettings() {+ $('#sets').innerHTML = Object.entries(spec).map(([k, s]) => `<div class="set" title="${esc(s.label)}"><span>${esc(s.label)}</span>` ++ (s.type === 'enum' ? `<select data-s="${k}">${s.values.map(v => `<option${v === settings[k] ? ' selected' : ''}>${v}</option>`).join('')}</select>`+ : s.type === 'bool' ? `<select data-s="${k}"><option${settings[k] ? ' selected' : ''}>on</option><option${!settings[k] ? ' selected' : ''}>off</option></select>`+ : `<input data-s="${k}" value="${settings[k]}">`) + `</div>`).join('');+}+$('#sets').addEventListener('change', async e => {+ const k = e.target.dataset.s; if (!k) return; let v = e.target.value;+ if (spec[k].type === 'bool') v = v === 'on'; if (spec[k].type === 'number') v = Number(v);+ const r = await (await fetch('settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ [k]: v, aiThread: 'ui (human)' }) })).json();+ if (r.ok) { settings = r.settings; toast('Saved'); compute(); } else { toast(r.error); renderSettings(); }+});+$('#gear').onclick = () => { renderSettings(); $('#modal').classList.add('on'); };+$('#close').onclick = () => $('#modal').classList.remove('on');+$('#modal').onclick = e => { if (e.target.id === 'modal') $('#modal').classList.remove('on'); };++(async () => {+ try {+ const s = await (await fetch('settings')).json(); settings = s.settings; spec = s.spec;+ const st = await (await fetch('state')).json(); seenRev = st.openRev || 0; $('#ver').textContent = 'v' + st.version; $('#sver').textContent = `hwcalc ${st.version} · port ${st.port}`;+ const hs = location.hash.slice(1); const [hc, hq] = hs.split('?');+ if (hc && CAT.find(c => c.id === hc)) { usedHash = true; select(hc, Object.fromEntries(new URLSearchParams(hq || ''))); }+ else select(st.ui.calc || 'divider', st.ui.inputs);+ } catch { select('divider'); }+ // backstop: an AI 'open' must land even if the SSE stream through the proxy drops or buffers+ setInterval(async () => { try { const st = await (await fetch('state', { cache: 'no-store' })).json();+ if ((st.openRev || 0) > seenRev) { seenRev = st.openRev; select(st.ui.calc, st.ui.inputs); toast(`Opened by ${st.openBy}`); } } catch {} }, 2500);+ const es = new EventSource('events');+ es.onmessage = e => { const m = JSON.parse(e.data);+ if (m.type === 'hello' && !usedHash && m.ui && m.ui.calc && (m.ui.calc !== cur || JSON.stringify(m.ui.inputs || {}) !== JSON.stringify(vals))) select(m.ui.calc, m.ui.inputs);+ if (m.type === 'open') { seenRev = Math.max(seenRev, m.rev || 0); select(m.ui.calc, m.ui.inputs); toast(`Opened by ${m.by}`); }+ if (m.type === 'settings') { settings = m.settings; compute(); } };+})();+</script>+</body></html>
schematics.jsadded+356@@ -0,0 +1,356 @@+/* hwcalc schematics — one SVG drawing per circuit calculator, labelled with the live inputs and results.+ * Shared by the browser UI and the server (GET /api/schematic). Pure string building, no DOM.+ * Kit: two-terminal parts (R, NTC, C, L, crystal, diode, LED, switch) placed between two grid points, plus+ * rails, grounds, terminals, op-amp, inverter, MOSFET, IC boxes, dimension arrows and PCB cross-section blocks. */+(function (root, factory) {+ if (typeof module === 'object' && module.exports) module.exports = factory(require('./calcs.js'));+ else root.HWSCHEM = factory(root.HWCALC);+})(typeof self !== 'undefined' ? self : this, function (H) {+ 'use strict';+ const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++ // ---------------------------------------------------------------- drawing kit+ function Kit() {+ const el = [];+ const k = {+ el,+ line(x1, y1, x2, y2, cls = 'w') { el.push(`<line class="${cls}" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"/>`); return k; },+ wire(...pts) { el.push(`<polyline class="w" points="${pts.map(p => p.join(',')).join(' ')}"/>`); return k; },+ dot(x, y) { el.push(`<circle class="dot" cx="${x}" cy="${y}" r="2.6"/>`); return k; },+ text(x, y, s, cls = 'n', anchor = 'middle') { if (s !== '' && s != null) el.push(`<text class="${cls}" x="${x}" y="${y}" text-anchor="${anchor}">${esc(s)}</text>`); return k; },+ rect(x, y, w, h, cls) { el.push(`<rect class="${cls}" x="${x}" y="${y}" width="${w}" height="${h}"/>`); return k; },+ raw(s) { el.push(s); return k; },++ /** A two-terminal part between (x1,y1) and (x2,y2) (axis-aligned). name/value labels sit beside the body. */+ part(kind, x1, y1, x2, y2, name = '', value = '', side = 'a') {+ const len = Math.hypot(x2 - x1, y2 - y1), ang = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI, cx = (x1 + x2) / 2, cy = (y1 + y2) / 2, h = len / 2;+ const body = BODY[kind] || BODY.R, b = body.half;+ el.push(`<g transform="translate(${cx},${cy}) rotate(${ang})"><line class="w" x1="${-h}" y1="0" x2="${-b}" y2="0"/><line class="w" x1="${b}" y1="0" x2="${h}" y2="0"/>${body.svg}</g>`);+ const vert = Math.abs(x2 - x1) < 1;+ if (vert) {+ const dx = side === 'l' ? -16 : side === 'r2' ? 26 : 16, an = side === 'l' ? 'end' : 'start';+ k.text(cx + dx, cy - 3, name, 'n', an); k.text(cx + dx, cy + 12, value, 'v', an);+ } else {+ const up = side !== 'b';+ k.text(cx, up ? cy - 16 : cy + 24, name, 'n'); k.text(cx, up ? cy + 26 : cy + 38, value, 'v');+ }+ return k;+ },+ gnd(x, y) { el.push(`<g class="w"><line x1="${x}" y1="${y}" x2="${x}" y2="${y + 10}"/><line x1="${x - 10}" y1="${y + 10}" x2="${x + 10}" y2="${y + 10}"/><line x1="${x - 6}" y1="${y + 14}" x2="${x + 6}" y2="${y + 14}"/><line x1="${x - 2}" y1="${y + 18}" x2="${x + 2}" y2="${y + 18}"/></g>`); return k; },+ rail(x, y, label, value = '') { el.push(`<g class="w"><line x1="${x}" y1="${y}" x2="${x}" y2="${y - 10}"/><line x1="${x - 10}" y1="${y - 10}" x2="${x + 10}" y2="${y - 10}"/></g>`);+ k.text(x + 14, y - 7, label, 'n', 'start'); return value ? k.text(x + 14 + label.length * 8.5 + 6, y - 7, value, 'v', 'start') : k; },+ /** Open terminal with a label; dir = side the label goes ('l' or 'r'). */+ term(x, y, label, value = '', dir = 'l') { el.push(`<circle class="term" cx="${x}" cy="${y}" r="3.5"/>`);+ const an = dir === 'l' ? 'end' : 'start', dx = dir === 'l' ? -9 : 9;+ k.text(x + dx, y + 4, label, 'n', an); return value ? k.text(x + dx, y + 18, value, 'v', an) : k; },+ /** Op-amp with its back edge at x, centred on y; top input at y−15, bottom y+15, output (x+56, y). */+ opamp(x, y, plusTop, label = '') {+ el.push(`<polygon class="w" points="${x},${y - 32} ${x},${y + 32} ${x + 56},${y}"/>`);+ k.text(x + 8, y - 11, plusTop ? '+' : '−', 'n', 'start'); k.text(x + 8, y + 19, plusTop ? '−' : '+', 'n', 'start');+ return label ? k.text(x + 28, y + 48, label, 'v', 'middle') : k;+ },+ /** Inverter between (x, y) and (x+60, y). */+ inverter(x, y) { el.push(`<g class="w"><line x1="${x}" y1="${y}" x2="${x + 14}" y2="${y}"/><polygon points="${x + 14},${y - 14} ${x + 14},${y + 14} ${x + 40},${y}"/><circle cx="${x + 44}" cy="${y}" r="4"/><line x1="${x + 48}" y1="${y}" x2="${x + 60}" y2="${y}"/></g>`); return k; },+ /** N-MOSFET: gate pin (x−22, y), drain pin (x+10, y−26), source pin (x+10, y+26). */+ nmos(x, y, name = '', value = '') {+ el.push(`<g class="w"><line x1="${x - 22}" y1="${y}" x2="${x - 8}" y2="${y}"/><line x1="${x - 8}" y1="${y - 12}" x2="${x - 8}" y2="${y + 12}"/>` ++ `<line x1="${x - 3}" y1="${y - 15}" x2="${x - 3}" y2="${y - 6}"/><line x1="${x - 3}" y1="${y - 4}" x2="${x - 3}" y2="${y + 4}"/><line x1="${x - 3}" y1="${y + 6}" x2="${x - 3}" y2="${y + 15}"/>` ++ `<polyline points="${x - 3},${y - 11} ${x + 10},${y - 11} ${x + 10},${y - 26}"/><polyline points="${x - 3},${y + 11} ${x + 10},${y + 11} ${x + 10},${y + 26}"/><polyline points="${x - 3},${y} ${x + 10},${y} ${x + 10},${y + 11}"/></g>` ++ `<polygon class="fill" points="${x - 2},${y} ${x + 5},${y - 4} ${x + 5},${y + 4}"/>`);+ k.text(x + 18, y - 3, name, 'n', 'start'); return k.text(x + 18, y + 12, value, 'v', 'start');+ },+ box(x, y, w, h, title, sub = '') { k.rect(x, y, w, h, 'box'); k.text(x + w / 2, y + h / 2 + (sub ? -2 : 4), title, 'n'); return sub ? k.text(x + w / 2, y + h / 2 + 13, sub, 'v') : k; },+ pinLabel(x, y, s, anchor = 'start') { return k.text(x, y, s, 'pin', anchor); },+ /** Dimension arrow between two points with a label at the middle (offset by dx, dy). */+ dim(x1, y1, x2, y2, label, dx = 0, dy = -6, anchor = 'middle') {+ el.push(`<line class="dim" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" marker-start="url(#hwa)" marker-end="url(#hwa)"/>`);+ return k.text((x1 + x2) / 2 + dx, (y1 + y2) / 2 + dy, label, 'v', anchor);+ },+ svg(w, h, caption = '') {+ return `<svg xmlns="http://www.w3.org/2000/svg" class="hwschem" viewBox="0 0 ${w} ${h + (caption ? 18 : 0)}" role="img" aria-label="${esc(caption || 'schematic')}">` ++ `<defs><marker id="hwa" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,1 L9,5 L0,9 z" class="fill"/></marker></defs>` ++ `<style>${STYLE}</style>${el.join('')}` + (caption ? `<text class="cap" x="${w / 2}" y="${h + 12}" text-anchor="middle">${esc(caption)}</text>` : '') + `</svg>`;+ },+ };+ return k;+ }+ const STYLE = '.hwschem .w,.hwschem .dim{stroke:#c9d1d9;stroke-width:1.6;fill:none;stroke-linejoin:round;stroke-linecap:round}' ++ '.hwschem .dim{stroke:#7fd8d2;stroke-width:1.1}.hwschem .fill{fill:#c9d1d9;stroke:none}.hwschem .dot{fill:#c9d1d9}' ++ '.hwschem .term{fill:#161b22;stroke:#c9d1d9;stroke-width:1.5}.hwschem .box{fill:#1b222c;stroke:#c9d1d9;stroke-width:1.5}' ++ '.hwschem .dash{stroke:#8b949e;stroke-width:1.2;fill:none;stroke-dasharray:5 4}' ++ '.hwschem text{font:12px Satoshi,system-ui,sans-serif;fill:#dfe6ee}.hwschem .v{fill:#2dd4c8;font-size:11.5px;font-weight:600}' ++ '.hwschem .pin{fill:#8b949e;font-size:10.5px}.hwschem .cap{fill:#8b949e;font-size:11px}' ++ '.hwschem .cu{fill:#c98a3e;stroke:#e0a458;stroke-width:1}.hwschem .fr4{fill:#24463c;stroke:#2f5a4d;stroke-width:1}.hwschem .air{fill:#0f141a}';++ // Part bodies in local coordinates (horizontal, centred on the origin); half = half-length of the body.+ const ZIG = '-20,0 -17.5,-6 -12.5,6 -7.5,-6 -2.5,6 2.5,-6 7.5,6 12.5,-6 17.5,6 20,0';+ const BODY = {+ R: { half: 20, svg: `<polyline class="w" points="${ZIG}"/>` },+ NTC: { half: 20, svg: `<polyline class="w" points="${ZIG}"/><polyline class="w" points="-22,12 -15,12 15,-12"/>` },+ C: { half: 4, svg: '<line class="w" x1="-4" y1="-12" x2="-4" y2="12"/><line class="w" x1="4" y1="-12" x2="4" y2="12"/>' },+ L: { half: 20, svg: '<path class="w" d="M-20,0 a5,5 0 0 1 10,0 a5,5 0 0 1 10,0 a5,5 0 0 1 10,0 a5,5 0 0 1 10,0"/>' },+ X: { half: 10, svg: '<line class="w" x1="-10" y1="-11" x2="-10" y2="11"/><line class="w" x1="10" y1="-11" x2="10" y2="11"/><rect class="box" x="-5" y="-13" width="10" height="26"/>' },+ D: { half: 9, svg: '<polygon class="w" points="-9,-9 -9,9 7,0"/><line class="w" x1="7" y1="-9" x2="7" y2="9"/><line class="w" x1="-9" y1="0" x2="7" y2="0"/>' },+ LED: { half: 9, svg: '<polygon class="w" points="-9,-9 -9,9 7,0"/><line class="w" x1="7" y1="-9" x2="7" y2="9"/><line class="w" x1="-9" y1="0" x2="7" y2="0"/>' ++ '<g class="w"><line x1="-2" y1="-11" x2="4" y2="-19"/><line x1="4" y1="-11" x2="10" y2="-19"/></g><polygon class="fill" points="4,-19 0.8,-17.6 3.2,-15.8"/><polygon class="fill" points="10,-19 6.8,-17.6 9.2,-15.8"/>' },+ SW: { half: 14, svg: '<circle class="term" cx="-12" cy="0" r="2.5"/><circle class="term" cx="12" cy="0" r="2.5"/><line class="w" x1="-10" y1="-1" x2="12" y2="-12"/>' },+ };++ // ---------------------------------------------------------------- value helpers+ function ctx(id, r) {+ const calc = H.CALCS.find(c => c.id === id);+ const vin = key => {+ const f = calc.inputs.find(q => q.key === key), x = r.inputs[key];+ if (!f || x === undefined || (typeof x === 'number' && !Number.isFinite(x))) return '';+ if (f.type === 'select' || f.type === 'text') return String(x);+ return f.si === false ? `${H.fmtN(x, '', 3)}${f.unit ? ' ' + f.unit : ''}` : H.fmtSI(x, f.unit || '');+ };+ const vo = prefix => { const o = (r.outputs || []).find(q => q.label.startsWith(prefix)); return o ? o.text : ''; };+ return { vin, vo, v: r.inputs, ok: r.ok };+ }++ // ---------------------------------------------------------------- drawings (id -> (kit, ctx) -> svg)+ const D = {};++ D.divider = (k, { vin, vo, v }) => {+ const design = v.mode === 'design';+ k.rail(140, 38, 'Vin', vin('Vin')).part('R', 140, 38, 140, 108, 'R1', design ? vo('Best R1') : vin('R1')).dot(140, 108)+ .wire([140, 108], [330, 108]).term(330, 108, 'Vout', design ? vo('Output') : vo('Output voltage'), 'r')+ .part('R', 140, 108, 140, 178, 'R2', design ? vo('Best R2') : vin('R2')).gnd(140, 178);+ if (!design && Number.isFinite(v.RL)) k.dot(250, 108).part('R', 250, 108, 250, 178, 'RL', vin('RL')).gnd(250, 178);+ return k.svg(440, 202, 'Vout = Vin · R2 / (R1 + R2)');+ };++ D.led = (k, { vin, vo, v }) => {+ const n = Math.max(1, Math.round(v.n) || 1), show = Math.min(n, 2);+ k.rail(160, 34, 'Vs', vin('Vs')).part('R', 160, 34, 160, 96, 'R', vo('Next'));+ let y = 96; for (let i = 0; i < show; i++) { k.part('LED', 160, y, 160, y + 50, i ? '' : 'LED', i ? '' : `Vf ${vin('Vf')} · ${vin('If')}`, 'r2'); y += 50; }+ if (n > 2) k.text(210, y - 22, `× ${n} in series`, 'pin', 'start');+ return k.gnd(160, y).svg(440, y + 24, `R = (Vs − n·Vf) / If`);+ };++ D.filter = (k, { vin, vo, v }) => {+ const [s, sh, sn, shn] = { RC: ['R', 'C', vin('R'), vin('C')], RL: ['L', 'R', vin('L'), vin('R')], LC: ['L', 'C', vin('L'), vin('C')] }[v.mode] || ['R', 'C', '', ''];+ k.term(50, 70, 'in').part(s, 50, 70, 190, 70, s, sn).dot(230, 70).wire([190, 70], [340, 70]).term(340, 70, 'out', '', 'r')+ .part(sh, 230, 70, 230, 150, sh, shn).gnd(230, 150);+ return k.svg(440, 176, v.mode === 'LC' ? `LC low-pass · f0 ${vo('Resonant')} · √(L/C) ${vo('Characteristic')}` : `${v.mode} low-pass · f−3dB ${vo('−3 dB')} · τ ${vo('Time constant')}`);+ };++ D.ldo = (k, { vin, vo }) => {+ k.term(40, 70, 'Vin', vin('Vin')).wire([40, 70], [150, 70]).box(150, 45, 110, 55, 'LDO', `Pd ${vo('Dissipation')}`).pinLabel(155, 64, 'IN').pinLabel(255, 64, 'OUT', 'end')+ .wire([205, 100], [205, 150]).gnd(205, 150).pinLabel(210, 112, 'GND').wire([260, 70], [340, 70]).dot(340, 70)+ .part('R', 340, 70, 340, 150, 'load', vin('Iout')).gnd(340, 150).wire([340, 70], [400, 70]).term(400, 70, '', '', 'r').text(400, 55, `Vout ${vin('Vout')}`, 'n', 'end');+ return k.svg(440, 176, `Tj = Ta + Pd·θJA = ${vo('Junction')}`);+ };++ D.buck = (k, { vin, vo }) => {+ k.term(70, 60, 'Vin', vin('Vin')).part('SW', 70, 60, 150, 60, 'Q1', `D = ${vo('Duty')}`).dot(150, 60).part('D', 150, 150, 150, 60, 'D1', '', 'l').gnd(150, 150)+ .part('L', 150, 60, 270, 60, 'L', `≥ ${vo('Minimum inductance')}`).dot(290, 60).wire([270, 60], [400, 60])+ .part('C', 290, 60, 290, 150, 'Cout', vin('Cout')).gnd(290, 150).dot(370, 60).part('R', 370, 60, 370, 150, 'load', vin('Iout')).gnd(370, 150).term(400, 60, '', '', 'r').text(400, 45, `Vout ${vin('Vout')}`, 'n', 'end');+ return k.svg(440, 176, `ΔIL ${vo('Ripple current')} · Ipk ${vo('Peak')} · fsw ${vin('fsw')} (synchronous: D1 → low-side FET)`);+ };++ D.boost = (k, { vin, vo }) => {+ k.term(70, 60, 'Vin', vin('Vin')).part('L', 70, 60, 160, 60, 'L', `≥ ${vo('Minimum inductance')}`).dot(170, 60).wire([160, 60], [170, 60])+ .part('SW', 170, 60, 170, 150, 'Q1', `D = ${vo('Duty')}`, 'l').gnd(170, 150).part('D', 170, 60, 280, 60, 'D1').dot(290, 60).wire([280, 60], [400, 60])+ .part('C', 290, 60, 290, 150, 'Cout', vin('Cout')).gnd(290, 150).dot(370, 60).part('R', 370, 60, 370, 150, 'load', vin('Iout')).gnd(370, 150).term(400, 60, '', '', 'r').text(400, 45, `Vout ${vin('Vout')}`, 'n', 'end');+ return k.svg(440, 176, `Ipk ${vo('Peak switch')} · fsw ${vin('fsw')}`);+ };++ D.holdup = (k, { vin, vo, v }) => {+ const C = v.mode === 'time' ? vin('C') : vo('Required capacitance'), load = v.load === 'constant power' ? vin('P') : vin('I');+ k.term(80, 60, 'bus in').part('D', 80, 60, 150, 60, 'D (OR-ing)').dot(190, 60).wire([150, 60], [320, 60]).part('C', 190, 60, 190, 150, 'C hold', C).gnd(190, 150)+ .dot(320, 60).part('R', 320, 60, 320, 150, 'load', load).gnd(320, 150);+ return k.svg(440, 176, `bus falls from V1 ${vin('V1')} to V2 ${vin('V2')} after the input drops`);+ };++ D.i2c = (k, { vin, vo }) => {+ k.box(20, 90, 64, 44, 'MCU').box(356, 90, 64, 44, 'device').rail(170, 30, 'VDD', vin('VDD')).part('R', 170, 30, 170, 112, 'Rp', vo('Suggested'))+ .dot(170, 112).wire([84, 112], [356, 112]).text(250, 106, 'SDA / SCL', 'pin').dot(290, 112).raw('<line class="dash" x1="290" y1="112" x2="290" y2="134"/>')+ .part('C', 290, 134, 290, 170, '', '').raw('<line class="dash" x1="290" y1="170" x2="290" y2="180"/>').gnd(290, 180).text(304, 150, `Cb ${vin('Cb')} (bus)`, 'v', 'start');+ return k.svg(440, 208, `Rp ${vo('Minimum')} … ${vo('Maximum')} · one pull-up per line`);+ };++ D.crystal = (k, { vin, vo, v }) => {+ const caps = v.mode === 'caps for target CL', C1 = caps ? vo('Nearest') : vin('C1'), C2 = caps ? vo('Nearest') : vin('C2');+ k.rect(100, 12, 250, 78, 'dash').text(342, 28, 'MCU', 'pin', 'end')+ .wire([130, 90], [130, 52], [175, 52]).inverter(175, 52).wire([235, 52], [310, 52], [310, 90]).dot(150, 52).dot(290, 52)+ .wire([150, 52], [150, 30]).part('R', 150, 30, 290, 30).text(246, 26, 'Rf', 'pin', 'start').wire([290, 30], [290, 52])+ .pinLabel(126, 104, 'OSC_IN', 'end').pinLabel(318, 104, 'OSC_OUT')+ .wire([130, 90], [130, 150]).part('R', 310, 90, 310, 150, 'RExt', 'optional').part('X', 130, 150, 310, 150, 'Y1', `CL ${vin('CL')}${v.F ? ' · ' + vin('F') : ''}`, 'b')+ .dot(130, 150).dot(310, 150).part('C', 130, 150, 130, 210, 'C1', C1, 'l').gnd(130, 210).part('C', 310, 150, 310, 210, 'C2', C2).gnd(310, 210);+ return k.svg(440, 234, `CL = C1·C2/(C1+C2) + Cs = ${vo('Load the crystal')} (Cs ${vin('Cs')} stray)`);+ };++ D.shunt = (k, { vin, vo }) => {+ k.term(70, 60, 'supply').part('R', 70, 60, 170, 60, 'Rshunt', vin('R')).dot(80, 60).dot(150, 60).wire([170, 60], [380, 60])+ .wire([80, 60], [80, 146], [200, 146]).wire([150, 60], [150, 116], [200, 116]).opamp(200, 131, false, `G ${vin('G')}`).wire([256, 131], [270, 131])+ .box(270, 111, 76, 40, 'ADC', `${vin('bits')} bit`).dot(380, 60).wire([380, 60], [410, 60]).part('R', 410, 60, 410, 180, 'load', vin('I'), 'l').gnd(410, 180);+ return k.svg(440, 204, `Vsense ${vo('Sense voltage')} · Kelvin-connect the sense lines at the shunt pads`);+ };++ D.thermal = (k, { vin, vo, v }) => {+ const heat = v.mode === 'junction temperature';+ k.text(40, 50, 'Tj', 'n').text(40, 64, heat ? vo('Junction') : vin('Tj'), 'v').dot(40, 80).part('R', 40, 80, 150, 80, 'θJC', vin('jc'), 'b')+ .dot(150, 80).text(150, 50, 'case', 'n').text(150, 64, vo('Case'), 'v').part('R', 150, 80, 260, 80, 'θCS', vin('cs'), 'b')+ .dot(260, 80).text(260, 50, 'heatsink', 'n').text(260, 64, vo('Heatsink'), 'v').part('R', 260, 80, 370, 80, 'θSA', heat ? vin('sa') : vo('Required') || vo('Heatsink'), 'b')+ .dot(370, 80).text(370, 50, 'ambient', 'n').text(370, 64, vin('Ta'), 'v').wire([370, 80], [370, 150]).gnd(370, 150)+ .raw('<circle class="w" cx="40" cy="130" r="14"/><line class="w" x1="40" y1="138" x2="40" y2="122"/><polygon class="fill" points="40,118 36,125 44,125"/>')+ .wire([40, 80], [40, 116]).wire([40, 144], [40, 150]).gnd(40, 150).text(62, 134, `P ${vin('P')}`, 'v', 'start');+ return k.svg(440, 176, 'Heat flows like current: ΔT = P · Σθ');+ };++ D.regulator = (k, { vin, vo, v }) => {+ const target = v.mode.startsWith('R2');+ k.term(40, 60, 'Vin').wire([40, 60], [150, 60]).box(150, 38, 110, 56, 'LM317', `Vref ${vin('Vref')}`).pinLabel(155, 56, 'IN').pinLabel(255, 56, 'OUT', 'end')+ .wire([260, 60], [380, 60]).dot(320, 60).term(400, 60, 'Vout', target ? vin('Vout') : vo('Output voltage'), 'r')+ .part('R', 320, 60, 320, 140, 'R1', vin('R1')).dot(320, 140).wire([320, 140], [205, 140], [205, 94]).pinLabel(210, 108, 'ADJ')+ .part('R', 320, 140, 320, 210, 'R2', target ? vo('Nearest') : vin('R2')).gnd(320, 210);+ return k.svg(440, 234, 'Vout = Vref·(1 + R2/R1) + Iadj·R2');+ };++ D.mosfet = (k, { vin, vo }) => {+ k.rail(200, 34, 'V', vin('V')).part('R', 200, 34, 200, 96, 'load', vin('I')).nmos(190, 122, 'Q1', `Rds(on) ${vin('Rds')}`).gnd(200, 148)+ .term(100, 122, 'gate drive', `${vin('Vgs')} · ${vin('fsw')}`).wire([100, 122], [168, 122]);+ return k.svg(440, 176, `Total loss ${vo('Total')} (conduction ${vo('Conduction')} + switching ${vo('Switching')})`);+ };++ D.opamp = (k, { vin, vo, v }) => {+ if (v.cfg === 'inverting') {+ k.term(40, 95, 'in').part('R', 40, 95, 150, 95, 'Rg', vin('Rg')).dot(160, 95).wire([150, 95], [200, 95]).opamp(200, 110, false)+ .wire([200, 125], [185, 125], [185, 140]).gnd(185, 140).wire([160, 95], [160, 40]).part('R', 160, 40, 300, 40, 'Rf', vin('Rf')).wire([300, 40], [300, 110])+ .wire([256, 110], [380, 110]).dot(300, 110).term(380, 110, 'out', `gain ${vo('Gain')}`, 'r');+ return k.svg(440, 170, 'G = −Rf/Rg');+ }+ k.term(60, 95, 'in').wire([60, 95], [200, 95]).opamp(200, 110, true).wire([200, 125], [170, 125]).dot(170, 125).wire([170, 125], [170, 165])+ .dot(170, 165).part('R', 170, 165, 300, 165, 'Rf', vin('Rf'), 'b').wire([300, 165], [300, 110]).part('R', 170, 165, 170, 230, 'Rg', vin('Rg'), 'l').gnd(170, 230)+ .wire([256, 110], [380, 110]).dot(300, 110).term(380, 110, 'out', `gain ${vo('Gain')}`, 'r');+ return k.svg(440, 256, 'G = 1 + Rf/Rg');+ };++ D.timer555 = (k, { vin, vo, v }) => {+ k.box(170, 40, 100, 150, '555', '').pinLabel(176, 74, '7 DIS').pinLabel(176, 134, '6 THR').pinLabel(176, 164, '2 TRIG').pinLabel(264, 104, 'OUT 3', 'end')+ .pinLabel(204, 55, '8').pinLabel(234, 55, '4').pinLabel(204, 184, '1').pinLabel(234, 184, '5')+ .wire([240, 40], [240, 26], [200, 26]).dot(200, 26).wire([200, 40], [200, 26]).rail(200, 26, 'VCC').wire([200, 190], [200, 205]).gnd(200, 205)+ .text(244, 204, 'CV: 10 nF to GND', 'pin', 'start').wire([270, 100], [360, 100]).term(360, 100, 'out', v.mode === 'astable' ? vo('Frequency') : vo('Pulse'), 'r');+ if (v.mode === 'astable') {+ k.rail(100, 26, 'VCC').part('R', 100, 26, 100, 70, 'RA', vin('RA'), 'l').dot(100, 70).wire([100, 70], [170, 70]).part('R', 100, 70, 100, 130, 'RB', vin('RB'), 'l')+ .dot(100, 130).wire([100, 130], [170, 130]).wire([100, 130], [100, 160]).dot(100, 160).wire([100, 160], [170, 160]).part('C', 100, 160, 100, 215, 'C', vin('C'), 'l').gnd(100, 215);+ return k.svg(440, 240, 'f = 1.44 / ((RA + 2·RB)·C)');+ }+ k.rail(100, 26, 'VCC').part('R', 100, 26, 100, 70, 'R', vin('R'), 'l').dot(100, 70).wire([100, 70], [170, 70]).wire([100, 70], [100, 130]).dot(100, 130).wire([100, 130], [170, 130])+ .part('C', 100, 130, 100, 200, 'C', vin('C'), 'l').gnd(100, 200).wire([170, 160], [140, 160], [140, 222]).term(140, 222, 'trigger ↓', '', 'r');+ return k.svg(440, 240, 't = 1.1 · R · C');+ };++ D.ntc = (k, { vin, vo, v }) => {+ k.rail(150, 34, 'Vcc', vin('Vcc')).part('R', 150, 34, 150, 104, 'Rp', vin('Rp')).dot(150, 104).wire([150, 104], [320, 104]).term(320, 104, 'to ADC', vo('Divider'), 'r')+ .part('NTC', 150, 104, 150, 174, 'NTC', `R25 ${vin('R25')} · β ${vin('B')}`).gnd(150, 174);+ return k.svg(440, 198, `at ${v.mode.startsWith('resistance') ? vin('T') : vo('Temperature')}: R = ${v.mode.startsWith('resistance') ? vo('Resistance') : vin('R')}`);+ };++ D.attenuator = (k, { vin, vo }) => {+ k.text(110, 22, 'Pi', 'n').term(34, 60, '').part('R', 50, 60, 160, 60, '', vo('Pi: series'), 'a').wire([34, 60], [50, 60]).wire([160, 60], [180, 60]).term(180, 60, '', '', 'r')+ .dot(50, 60).dot(160, 60).part('R', 50, 60, 50, 140).gnd(50, 140).part('R', 160, 60, 160, 140, '', vo('Pi: shunt'), 'r').gnd(160, 140)+ .text(325, 22, 'Tee', 'n').term(236, 60, '').part('R', 236, 60, 325, 60, '', vo('Tee: series')).part('R', 325, 60, 414, 60, '', '').term(414, 60, '', '', 'r')+ .dot(325, 60).part('R', 325, 60, 325, 140, '', vo('Tee: shunt')).gnd(325, 140);+ return k.svg(440, 166, `${vin('dB')} in ${vin('Z')} (matched both ends)`);+ };++ D.rlc = (k, { vin, vo, v }) => {+ if (v.cfg === 'parallel') {+ k.term(60, 40, 'a').term(60, 150, 'b').wire([60, 40], [320, 40]).wire([60, 150], [320, 150]);+ [['R', 140, vin('R')], ['L', 230, vin('L')], ['C', 320, vin('C')]].forEach(([p, x, val], i) => { k.part(p, x, 40, x, 150, p, val); if (i < 2) k.dot(x, 40).dot(x, 150); });+ return k.svg(440, 174, `f0 ${vo('Resonant')} · Q ${vo('Q')}`);+ }+ k.term(30, 80, 'a').part('R', 30, 80, 150, 80, 'R', vin('R')).part('L', 150, 80, 270, 80, 'L', vin('L')).part('C', 270, 80, 380, 80, 'C', vin('C')).term(380, 80, 'b', '', 'r');+ return k.svg(440, 140, `f0 ${vo('Resonant')} · Q ${vo('Q')} · |Z| at ${vin('f')} = ${vo('|Z|')}`);+ };++ D.combine = (k, { vo, v }) => {+ const p = { resistors: ['R', 'Ω'], capacitors: ['C', 'F'], inductors: ['L', 'H'] }[v.kind] || ['R', 'Ω'];+ const vals = String(v.list || '').split(/[\s,;]+/).filter(Boolean), shown = vals.slice(0, 4), more = vals.length - shown.length;+ const lab = s => { const x = H.parseNum(s); return Number.isFinite(x) ? H.fmtSI(x, p[1]) : s; };+ if (v.cfg === 'parallel') {+ const x0 = 110, dx = 90, xs = shown.map((_, i) => x0 + i * dx), xe = xs[xs.length - 1] || x0;+ k.term(50, 40, 'a').term(50, 150, 'b').wire([50, 40], [xe, 40]).wire([50, 150], [xe, 150]);+ xs.forEach((x, i) => { k.part(p[0], x, 40, x, 150, p[0] + (i + 1), lab(shown[i])); if (i < xs.length - 1) k.dot(x, 40).dot(x, 150); });+ if (more > 0) k.text(xe + 50, 100, `+${more} more`, 'pin', 'start');+ return k.svg(440, 174, `Equivalent ${vo('Equivalent')}`);+ }+ const seg = Math.min(100, 340 / Math.max(1, shown.length)); let x = 40;+ k.term(x, 80, 'a'); shown.forEach((s, i) => { k.part(p[0], x, 80, x + seg, 80, p[0] + (i + 1), lab(s)); x += seg; }); k.term(x, 80, more > 0 ? `+${more}` : 'b', '', 'r');+ return k.svg(440, 140, `Equivalent ${vo('Equivalent')}`);+ };++ D.rfind = (k, { vin, vo }) => {+ const best = vo('Best'), par = /[∥‖]|\|\|/.test(best), [a, b] = best.split(/\s*(?:\+|[∥‖]|\|\|)\s*/);+ if (par) k.term(80, 40, 'a').term(80, 150, 'b').wire([80, 40], [300, 40]).wire([80, 150], [300, 150]).dot(190, 40).dot(190, 150)+ .part('R', 190, 40, 190, 150, 'R1', a || '').part('R', 300, 40, 300, 150, 'R2', b || '');+ else k.term(60, 80, 'a').part('R', 60, 80, 210, 80, 'R1', a || '').part('R', 210, 80, 360, 80, 'R2', b || '').term(360, 80, 'b', '', 'r');+ return k.svg(440, par ? 174 : 140, `target ${vin('target')} → ${vo('Gives')} (${vo('Error')})`);+ };++ // ---- PCB cross-sections (not to scale; labels are the entered dimensions)+ D.impedance = (k, { vin, vo, v }) => {+ const w = v.mode === 'width' ? vo('Trace width') : vin('w');+ if (v.geom === 'stripline') {+ k.rect(40, 40, 360, 8, 'cu').rect(40, 48, 360, 104, 'fr4').rect(40, 152, 360, 8, 'cu').rect(175, 94, 90, 12, 'cu')+ .dim(175, 80, 265, 80, `w ${w}`).dim(372, 48, 372, 152, `b ${vin('h')}`, -8, 4, 'end').text(60, 70, `εr ${vin('er')}`, 'n', 'start').text(220, 186, 'plane', 'pin').text(220, 32, 'plane', 'pin');+ return k.svg(440, 196, `${v.mode === 'width' ? 'for Z0 ' + vin('Z') : 'Z0 ' + vo('Impedance')} · trace centred between planes (not to scale)`);+ }+ k.rect(40, 90, 360, 70, 'fr4').rect(40, 160, 360, 8, 'cu').rect(175, 78, 90, 12, 'cu').dim(175, 62, 265, 62, `w ${w}`)+ .dim(372, 90, 372, 160, `h ${vin('h')}`, -8, 4, 'end').text(60, 130, `εr ${vin('er')}`, 'n', 'start').text(220, 186, 'reference plane', 'pin').text(290, 74, `${vin('oz')} Cu`, 'pin', 'start');+ return k.svg(440, 196, `${v.mode === 'width' ? 'for Z0 ' + vin('Z') : 'Z0 ' + vo('Impedance')} (not to scale)`);+ };++ D.diffpair = (k, { vin, vo, v }) => {+ const strip = v.geom === 'stripline', ty = strip ? 94 : 78;+ if (strip) k.rect(40, 40, 360, 8, 'cu').rect(40, 48, 360, 104, 'fr4').rect(40, 152, 360, 8, 'cu');+ else k.rect(40, 90, 360, 70, 'fr4').rect(40, 160, 360, 8, 'cu');+ k.rect(110, ty, 70, 12, 'cu').rect(210, ty, 70, 12, 'cu').text(145, ty - 4, 'P', 'pin').text(245, ty - 4, 'N', 'pin')+ .dim(110, ty - 16, 180, ty - 16, `w ${vin('w')}`).dim(180, ty + 26, 210, ty + 26, `s ${vin('s')}`, 0, 14)+ .dim(372, strip ? 48 : 90, 372, strip ? 152 : 160, `${strip ? 'b' : 'h'} ${vin('h')}`, -8, 4, 'end').text(60, strip ? 70 : 130, `εr ${vin('er')}`, 'n', 'start');+ return k.svg(440, 190, `Zdiff ${vo('Differential')} (not to scale)`);+ };++ D.trace = (k, { vin, vo, v }) => {+ const w = v.mode === 'width' ? vo('Minimum width') : vin('w'), internal = v.std === 'IPC-2221' && v.layer === 'internal';+ k.rect(40, 70, 360, 90, 'fr4').rect(160, internal ? 108 : 56, 120, 14, 'cu').dim(160, internal ? 96 : 42, 280, internal ? 96 : 42, `w ${w}`)+ .dim(300, internal ? 108 : 56, 300, internal ? 122 : 70, `${vin('oz')} (${vo('Copper thickness')})`, 8, 4, 'start');+ return k.svg(440, 176, `${v.mode === 'width' ? 'I ' + vin('I') : 'I max ' + vo('Maximum current')} for ΔT ${vin('dT')} · ${internal ? 'internal' : 'external'} layer`);+ };++ D.via = (k, { vin, vo }) => {+ k.rect(60, 50, 320, 120, 'fr4').rect(60, 106, 320, 8, 'cu').rect(185, 100, 70, 20, 'fr4')+ .rect(190, 50, 60, 120, 'air').rect(190, 50, 8, 120, 'cu').rect(242, 50, 8, 120, 'cu').rect(175, 44, 90, 6, 'cu').rect(175, 170, 90, 6, 'cu')+ .dim(198, 30, 242, 30, `drill ${vin('d')}`).dim(175, 194, 265, 194, `pad ${vin('pad')}`, 0, 16).dim(300, 50, 300, 170, `${vin('h')}`, 8, -26, 'start')+ .text(80, 102, 'plane', 'pin', 'start').text(80, 140, `antipad ${vin('anti')}`, 'pin', 'start').text(220, 140, `${vin('tp')}`, 'pin');+ return k.svg(440, 214, `R ${vo('DC resistance')} · L ${vo('Inductance')} · C ${vo('Pad capacitance')} (not to scale)`);+ };++ D.spacing = (k, { vin, vo }) => {+ k.rect(40, 90, 360, 60, 'fr4').rect(90, 76, 110, 14, 'cu').rect(250, 76, 110, 14, 'cu').text(145, 70, 'conductor A', 'pin').text(305, 70, 'conductor B', 'pin')+ .dim(200, 110, 250, 110, `≥ ${vo('Minimum spacing')}`, 0, 22).text(225, 50, `ΔV ${vin('V')}`, 'n');+ return k.svg(440, 160, 'IPC-2221 Table 6-1 minimum electrical clearance');+ };++ D.spiral = (k, { vin, vo, v }) => {+ const n = Math.max(1, Math.min(10, v.n || 1)), cx = 200, cy = 110, R = 80, r0 = Math.max(8, R * (v.din / v.dout || 0.3));+ const p = (R - r0) / n, pts = []; let r = R;+ const sides = v.shape === 'hexagonal' ? 6 : v.shape === 'octagonal' ? 8 : 4, off = sides === 4 ? Math.PI / 4 : Math.PI / sides;+ for (let i = 0; i <= n * sides; i++) { const a = off + i * 2 * Math.PI / sides; const rv = r / Math.cos(Math.PI / sides); pts.push([cx + rv * Math.cos(a), cy + rv * Math.sin(a)]); r -= p / sides; }+ k.raw(`<polyline class="w" style="stroke:#e0a458;stroke-width:3" points="${pts.map(q => q.map(z => z.toFixed(1)).join(',')).join(' ')}"/>`)+ .dim(cx - R, cy + R + 18, cx + R, cy + R + 18, `dout ${vin('dout')}`, 0, 16).dim(cx - r0, cy, cx + r0, cy, `din ${vin('din')}`, 0, -6)+ .text(330, 90, `${Math.round(v.n)} turns`, 'n', 'start').text(330, 108, vo('Inductance'), 'v', 'start');+ return k.svg(440, 236, `${v.shape} spiral (not to scale)`);+ };++ // ---------------------------------------------------------------- entry points+ function draw(id, raw = {}, settings = {}) {+ const fn = D[id]; if (!fn) return null;+ const r = H.run(id, raw, settings); if (!r.inputs) return null;+ try { return fn(Kit(), ctx(id, r)); } catch (e) { return null; }+ }+ return { draw, has: id => !!D[id], ids: Object.keys(D) };+});
server.jsadded+143@@ -0,0 +1,143 @@+#!/usr/bin/env node+/* hwcalc server — zero dependencies. Serves the UI, the calculator API, settings, and a live SSE channel.+ * Lifecycle per app-creator-server-lifecycle: registry entry, 24 h idle reaper, per-thread snapshot, --port auto. */+'use strict';+const http = require('http'), fs = require('fs'), path = require('path'), os = require('os'), { execFile } = require('child_process');+const H = require('./calcs.js'), S = require('./schematics.js');+const PKG = require('./package.json');++const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };+const THREAD = arg('--ai-thread', process.env.ADOM_AI_THREAD || 'hwcalc');+const KEEP_ALIVE = process.argv.includes('--keep-alive');+const APP = 'hwcalc';+const HOME = path.join(os.homedir(), '.adom', 'instances', APP);+const slug = s => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'default';+fs.mkdirSync(path.join(HOME, 'snapshots'), { recursive: true });+const REG = path.join(HOME, slug(THREAD) + '.json'), SNAP = path.join(HOME, 'snapshots', slug(THREAD) + '.json'), SETF = path.join(HOME, 'settings.json');++// ---------------------------------------------------------------- settings (server-side, persisted)+const SETTINGS_SPEC = {+ e_series: { type: 'enum', values: ['E6', 'E12', 'E24', 'E48', 'E96', 'E192'], def: 'E24', label: 'Default E-series for resistor picks' },+ trace_dT: { type: 'number', min: 1, max: 100, def: 10, label: 'Default trace temperature rise (°C)' },+ show_formulas: { type: 'bool', def: true, label: 'Show formula and reference under results' },+ show_schematics: { type: 'bool', def: true, label: 'Show the schematic / cross-section drawing' },+ ttl_hours: { type: 'number', min: 1, max: 720, def: 24, label: 'Shut the server down after this many idle hours' },+ default_surface: { type: 'enum', values: ['wv', 'pup'], def: 'wv', label: 'Where "hwcalc show" opens the app' },+};+let settings = Object.fromEntries(Object.entries(SETTINGS_SPEC).map(([k, s]) => [k, s.def]));+try { Object.assign(settings, JSON.parse(fs.readFileSync(SETF, 'utf8'))); } catch {}+const argTtl = arg('--ttl'); if (argTtl) settings.ttl_hours = Number(argTtl);+function validateSettings(patch) {+ const bad = [];+ for (const [k, v] of Object.entries(patch)) {+ const s = SETTINGS_SPEC[k]; if (!s) { bad.push(`unknown setting "${k}" (valid: ${Object.keys(SETTINGS_SPEC).join(', ')})`); continue; }+ if (s.type === 'enum' && !s.values.includes(v)) bad.push(`${k} must be one of ${s.values.join(', ')}`);+ if (s.type === 'number' && !(Number(v) >= s.min && Number(v) <= s.max)) bad.push(`${k} must be a number ${s.min}–${s.max}`);+ if (s.type === 'bool' && typeof v !== 'boolean') bad.push(`${k} must be true or false`);+ }+ return bad;+}++// ---------------------------------------------------------------- UI state + per-thread snapshot+let ui = { calc: 'divider', inputs: {} }; let openRev = 0, openBy = '';+try { const s = JSON.parse(fs.readFileSync(SNAP, 'utf8')); ui = { ...ui, ...s.ui }; console.log(`restored snapshot for thread "${THREAD}"`); } catch {}+let snapTimer = null;+const saveSnapshot = () => { try { fs.writeFileSync(SNAP, JSON.stringify({ thread: THREAD, savedAt: new Date().toISOString(), ui }, null, 1)); } catch (e) { log('snapshot write failed: ' + e.message); } };+const saveSoon = () => { clearTimeout(snapTimer); snapTimer = setTimeout(saveSnapshot, 1000); };++// ---------------------------------------------------------------- console ring buffer + SSE+const ring = []; const log = m => { const l = `${new Date().toISOString()} ${m}`; ring.push(l); if (ring.length > 300) ring.shift(); console.log(l); };+const clients = new Set();+const broadcast = msg => { const d = `data: ${JSON.stringify(msg)}\n\n`; for (const c of clients) c.write(d); };++// ---------------------------------------------------------------- lifecycle+let lastActivity = Date.now(), PORT = 0;+const writeReg = () => { try { fs.writeFileSync(REG, JSON.stringify({ pid: process.pid, port: PORT, thread: THREAD, task: 'hardware calculations', version: PKG.version,+ startedAt: START, lastActivity: new Date(lastActivity).toISOString(), dir: __dirname }, null, 1)); } catch {} };+const START = new Date().toISOString();+function reap(why) {+ log(`reaping (${why})`); saveSnapshot();+ try { fs.unlinkSync(REG); } catch {}+ execFile('adom-cli', ['hydrogen', 'workspace', 'remove-tab', '--name', 'Hardware Calculator'], () => process.exit(0));+ setTimeout(() => process.exit(0), 5000).unref();+}+if (!KEEP_ALIVE) setInterval(() => { if (Date.now() - lastActivity > settings.ttl_hours * 3600e3) reap(`idle ${settings.ttl_hours} h`); }, 60e3).unref();+setInterval(writeReg, 60e3).unref();+process.on('SIGTERM', () => reap('SIGTERM')); process.on('SIGINT', () => reap('SIGINT'));++// ---------------------------------------------------------------- http+const READ_ONLY = new Set(['/state', '/console', '/settings', '/events', '/version', '/api/catalog', '/api/calc', '/api/schematic']);+const UI_ONLY = new Set(['/ui/state']); // posted by the page itself (the human), not by an AI+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png' };+const json = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(obj)); };+const body = req => new Promise(r => { let b = ''; req.on('data', c => b += c); req.on('end', () => { try { r(b ? JSON.parse(b) : {}); } catch { r({ __bad: true }); } }); });++const server = http.createServer(async (req, res) => {+ lastActivity = Date.now();+ const url = new URL(req.url, 'http://x'), p = url.pathname;+ try {+ if (req.method === 'GET') {+ if (p === '/' || p === '/index.html') return file(res, path.join(__dirname, 'public', 'index.html'));+ if (p === '/calcs.js') return file(res, path.join(__dirname, 'calcs.js'));+ if (p === '/schematics.js') return file(res, path.join(__dirname, 'schematics.js'));+ if (p === '/api/schematic') { // GET /api/schematic?calc=<id>&key=value… -> image/svg+xml+ const q = Object.fromEntries(url.searchParams), id = q.calc; delete q.calc;+ const svg = S.draw(id, q, settings); if (!svg) return json(res, 404, { ok: false, error: `No schematic for "${id}".`, known: S.ids });+ res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store' }); return res.end(svg);+ }+ if (p.startsWith('/static/')) return file(res, path.join(__dirname, 'public', path.normalize(p.slice(8)).replace(/^(\.\.[/\\])+/, '')));+ if (p === '/version') return json(res, 200, { app: APP, version: PKG.version });+ if (p === '/state') return json(res, 200, { ok: true, app: APP, version: PKG.version, thread: THREAD, port: PORT, ui, openRev, openBy, clients: clients.size, settings, result: H.run(ui.calc, ui.inputs, settings) });+ if (p === '/settings') return json(res, 200, { ok: true, settings, spec: SETTINGS_SPEC });+ if (p === '/console') return json(res, 200, { ok: true, lines: ring.slice(-100) });+ if (p === '/api/catalog') return json(res, 200, { ok: true, calcs: H.catalog() });+ if (p === '/events') {+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });+ res.write(`data: ${JSON.stringify({ type: 'hello', ui, settings })}\n\n`); clients.add(res);+ const ka = setInterval(() => res.write(': ka\n\n'), 25e3); req.on('close', () => { clearInterval(ka); clients.delete(res); }); return;+ }+ return json(res, 404, { ok: false, error: 'not found' });+ }+ if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method not allowed' });+ const b = await body(req); if (b.__bad) return json(res, 400, { ok: false, error: 'body is not valid JSON' });++ if (!READ_ONLY.has(p) && !UI_ONLY.has(p) && !b.aiThread)+ return json(res, 400, { ok: false, errorCode: 'caller_identity_required', error: 'This app requires every AI caller to give its ai-thread name.',+ hint: 'Re-run with the global flag: hwcalc --ai-thread "<name>" <verb>, or add a top-level "aiThread" field if POSTing directly. Use a short human-recognizable name for THIS conversation and reuse it everywhere.' });++ if (p === '/api/calc') { // pure computation: open to everyone+ const r = H.run(b.calc, b.inputs || {}, settings); return json(res, r.ok || r.error ? 200 : 404, r);+ }+ if (p === '/api/open') { // drive the UI: select a calculator and fill inputs+ if (!H.CALCS.find(c => c.id === b.calc)) return json(res, 400, { ok: false, error: `Unknown calculator "${b.calc}".`, known: H.CALCS.map(c => c.id) });+ ui = { calc: b.calc, inputs: { ...(b.inputs || {}) } }; openRev++; openBy = b.aiThread; saveSoon();+ log(`thread "${b.aiThread}": open ${b.calc} ${JSON.stringify(b.inputs || {})}`);+ broadcast({ type: 'open', ui, by: b.aiThread, rev: openRev }); return json(res, 200, { ok: true, ui, result: H.run(ui.calc, ui.inputs, settings), clients: clients.size });+ }+ if (p === '/ui/state') { ui = { calc: b.calc, inputs: b.inputs || {} }; saveSoon(); return json(res, 200, { ok: true }); }+ if (p === '/settings') {+ const patch = { ...b }; delete patch.aiThread; delete patch.reason;+ const bad = validateSettings(patch); if (bad.length) return json(res, 400, { ok: false, errorCode: 'invalid_setting', error: bad.join('; '), spec: SETTINGS_SPEC });+ for (const [k, v] of Object.entries(patch)) settings[k] = SETTINGS_SPEC[k].type === 'number' ? Number(v) : v;+ fs.writeFileSync(SETF, JSON.stringify(settings, null, 1)); log(`settings ${JSON.stringify(patch)} by ${b.aiThread || 'ui'}`);+ broadcast({ type: 'settings', settings }); return json(res, 200, { ok: true, settings });+ }+ if (p === '/shutdown') {+ if (!b.reason) return json(res, 400, { ok: false, errorCode: 'reason_required', error: 'Shutting down closes the user\'s calculator tab.',+ hint: 'Re-run with --reason "<why>" (for example "user asked to close it"). The server also shuts itself down after the idle TTL.' });+ json(res, 200, { ok: true, bye: true }); log(`shutdown by "${b.aiThread}": ${b.reason}`); return setTimeout(() => reap('shutdown'), 200);+ }+ return json(res, 404, { ok: false, error: 'not found' });+ } catch (e) { log('error ' + e.stack); json(res, 500, { ok: false, error: String(e.message) }); }+});+function file(res, f) {+ fs.readFile(f, (err, d) => { if (err) return json(res, 404, { ok: false, error: 'not found' });+ res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream', 'Cache-Control': 'no-store' }); res.end(d); });+}++const want = arg('--port', 'auto');+server.listen(want === 'auto' ? 0 : Number(want), '0.0.0.0', () => {+ PORT = server.address().port; writeReg();+ log(`hwcalc ${PKG.version} listening on ${PORT} (thread "${THREAD}", ttl ${KEEP_ALIVE ? 'off' : settings.ttl_hours + ' h'})`);+ console.log(JSON.stringify({ ok: true, port: PORT, pid: process.pid }));+});
skills/hwcalc/SKILL.mdadded+71@@ -0,0 +1,71 @@+---+name: hwcalc+description: >+ Hardware Calculator (hwcalc) v0.3: an Adom app with 40 hardware design calculators in a Hydrogen webview UI, a CLI and an HTTP+ API sharing one formula module, each result showing its formula and standard, plus a live schematic or PCB cross-section+ labelled with the entered values for 26 of them. PCB: IPC-2152 (default) / IPC-2221 trace width and+ drop, IPC-2221C Table 6-1 conductor spacing, IPC-2141 microstrip/stripline and differential-pair impedance, via R/L/C/current,+ Onderdonk fusing current. Power: LDO, buck, boost, adjustable-regulator resistors, MOSFET losses, PDN target impedance, hold-up+ cap, battery life. Signal/RF: RC/RL/LC, RLC resonance, op-amp gain/bandwidth, 555, rise time/critical length, skin depth, dBm/W/V,+ VSWR/return loss, Pi/Tee attenuator, wavelength, planar spiral inductor. Components: E-series with colour/SMD codes, two-resistor+ combination finder, series/parallel, unit converter; plus divider, LED resistor, I2C pull-up, crystal caps, ppm, shunt, ADC, NTC,+ junction temperature, AWG; crystal oscillator load caps (CL, C1/C2, gm_crit and gain margin per ST AN2867,+ pulling, trim sensitivity, drive level). Use when the user asks to calculate, size or check any of these, or says hwcalc, hardware calculator,+ open the calculator, crystal load capacitors, oscillator caps, gain margin, trace width, clearance for voltage, diff pair impedance, via current, attenuator, VSWR, LM317 resistors.+---++# hwcalc — Hardware Calculator++Wiki page: https://wiki.adom.inc/adom/hardware-calculator (`adom-wiki pkg install adom/hardware-calculator`). Source: the installed module dir+(calcs.js = every formula, schematics.js = drawings, server.js, public/index.html, bin/hwcalc, test.js); every formula and its source is+listed in SOURCES.md.++## Displaying this app (REQUIRED — read before showing anything)++To SHOW this app, use `hwcalc --ai-thread "<name>" show` (it opens the proper Hydrogen webview tab itself); `start` shows+it too. For manual display, FIRST load the `webview` skill (adom-workspace-control) and follow it.+- **NEVER open this app in VS Code's "Simple Browser"** — not a webview in the Adom+ ecosystem: no live channel, no console read-back, no AI drivability. Using it is a bug.+- Surfaces: **wv** — Hydrogen webview panel (`webview` skill; Hydrogen's pane tab inside Hydrogen),+ **pup** (`pup` skill), the user's **real signed-in browser** (Adom browser extension),+ and **hdbw** — Hydrogen's standalone Tauri browser window (only under Hydrogen). Simple Browser is+ NEVER one of them. `hwcalc show --surface wv|pup`; the default is a Setting.++## Verbs++Every verb that changes something needs the global `--ai-thread "<name>"` flag (refusal code `caller_identity_required`).++```bash+hwcalc --ai-thread "<name>" start # reuses a live instance (any thread: the calculator keeps no per-thread state); --new for a private one+hwcalc ls # instances, idle time, version drift+hwcalc list # calculator ids and their inputs+hwcalc calc trace I=3 dT=20 oz=2 len=40 # compute from the CLI, no server needed; --json for machine output+hwcalc calc crystal CL=12p Cs=4p F=8M C0=7p ESR=80 gm=25m --svg osc.svg # --svg writes the labelled schematic+hwcalc --ai-thread "<name>" open buck Vin=12 Vout=3.3 Iout=2 fsw=500k # put a calculation in front of the user+hwcalc settings # read; add key=value (with --ai-thread) to change+hwcalc --ai-thread "<name>" shutdown --reason "<why>" # reason-gated; the server also reaps itself after 24 h idle+```++Values accept engineering prefixes: `4k7`, `10u`, `2.2M`, `100n`, `500k`. Select inputs take their option text (quote+values with spaces: `"speed=Fast 400 kHz"`).++## HTTP API (same port; relative paths from the page)++`GET /state /settings /console /version /api/catalog /events(SSE)` open; `GET /api/schematic?calc=<id>&key=value…` returns the SVG; `POST /api/calc {calc, inputs}` open (pure math);+`POST /api/open {aiThread, calc, inputs}` drives the UI; `POST /settings {aiThread, …}` validated against the enum spec;+`POST /shutdown {aiThread, reason}`.++## Lifecycle++Registry `~/.adom/instances/hwcalc/<thread>.json`, per-thread UI snapshot in `snapshots/`, settings in `settings.json`,+log in `server.log`. Idle TTL 24 h (Setting `ttl_hours`, `--ttl`, `--keep-alive`). `--port auto` by default.++## Adding or changing a calculator++Every calculator here was verified against its standard or a primary source, has a test reproducing the source's own+worked example, and (when it describes a circuit or PCB structure) a labelled drawing. Changes must meet the same bar: follow+the `hwcalc-calculator-standards` skill in the page's Dev skills (`adom-wiki repo clone adom/hardware-calculator`,+`dev-skills/`). Releases follow `publish-skills/hwcalc-release`.++Standards register (revision + date checked for each source): `SOURCES.md` in the module dir.+`Copy link` in the UI gives `…/#<calc-id>?key=value` URLs that reopen a calculation.
test.jsadded+114@@ -0,0 +1,114 @@+// hwcalc self-test: every calculator against hand-checked reference values. node test.js+const H = require('./calcs.js');+let fail = 0, n = 0;+const near = (a, b, tol) => Math.abs(a - b) <= Math.abs(b) * tol;+function check(name, got, want, tol = 0.01) {+ n++; const ok = typeof want === 'string' ? got === want : near(got, want, tol);+ if (!ok) { fail++; console.log(`FAIL ${name}: got ${got}, want ${want}`); }+}+const o = (r, label) => { const x = r.outputs.find(q => q.label.startsWith(label)); if (!x) throw new Error(`${r.calc}: no output "${label}" (${r.error || ''})`); return x.value; };++// parsing+check('parse 4k7', H.parseNum('4k7'), 4700); check('parse 10u', H.parseNum('10u'), 1e-5); check('parse 2.2M', H.parseNum('2.2M'), 2.2e6);+check('parse 100nF', H.parseNum('100nF'), 1e-7); check('parse 5m', H.parseNum('5m'), 5e-3); check('parse 1e-3', H.parseNum('1e-3'), 1e-3);+check('parse 3R3?', H.parseNum('3.3'), 3.3); check('parse plain mm', H.parseNum('5', false), 5);+// E-series+check('E96[0]', H.E_BASE.E96[0], 1.00); check('E96 1.02', H.E_BASE.E96[1], 1.02); check('E96 4.75', H.E_BASE.E96.includes(4.75) ? 1 : 0, 1);+check('E96 9.76', H.E_BASE.E96[95], 9.76); check('E192 9.20', H.E_BASE.E192.includes(9.2) ? 1 : 0, 1);+check('nearest E24 4.8k', H.eNearest(4800, 'E24').nearest, 4700); check('E12 above 470', H.eNearest(471, 'E12').above, 560);+check('EIA96 4.75k', H.eia96(4750), '66B'); check('EIA96 10k', H.eia96(10000), '01C');+check('bands 4.7k', H.colourBands(4700, 2).join(','), 'yellow,violet,red');++// calculators+let r = H.run('ohms', { V: '5', I: '10m' }); check('ohms R', o(r, 'Resistance'), 500); check('ohms P', o(r, 'Power'), 0.05);+r = H.run('ohms', { V: '', I: '', R: '100', P: '0.25' }); check('ohms RP→V', o(r, 'Voltage'), 5);+r = H.run('divider', { Vin: '12', R1: '10k', R2: '3k3' }); check('divider Vout', o(r, 'Output voltage'), 12 * 3300 / 13300);+r = H.run('divider', { Vin: '12', R1: '10k', R2: '10k', RL: '10k' }); check('divider loaded', o(r, 'Output voltage'), 4);+r = H.run('divider', { mode: 'design', Vin: '5', Vout: '3.3', Rtot: '100k', series: 'E96' }); check('divider design err<0.5%', Math.abs(o(r, 'Error')) < 0.5 ? 1 : 0, 1);+r = H.run('led', { Vs: '5', Vf: '2', n: '1', If: '10m', series: 'E24' }); check('led R', o(r, 'Exact'), 300); check('led E24', o(r, 'Next E24'), 300);+r = H.run('filter', { mode: 'RC', R: '10k', C: '100n' }); check('RC fc', o(r, '−3 dB'), 159.155);+r = H.run('filter', { mode: 'LC', L: '10u', C: '100n' }); check('LC f0', o(r, 'Resonant'), 159155);+// IPC-2221: 1 A, 10 °C rise, 1 oz external -> ~11.8 mil (standard calculators give 11.8)+r = H.run('trace', { std: 'IPC-2221', mode: 'width', I: '1', dT: '10', oz: '1', layer: 'external', len: '50' }); check('IPC-2221 1A ext', o(r, 'Width'), 11.8, 0.02);+r = H.run('trace', { std: 'IPC-2221', mode: 'width', I: '1', dT: '10', oz: '1', layer: 'internal', len: '50' }); check('IPC-2221 1A int', o(r, 'Width'), 30.7, 0.02);+r = H.run('trace', { std: 'IPC-2221', mode: 'current', w: String(11.8 * 0.0254), dT: '10', oz: '1', layer: 'external' }); check('IPC-2221 inverse', o(r, 'Maximum current'), 1, 0.02);+// IPC-2141 microstrip: h 0.2 mm, w 0.35, t 35 µm, er 4.5 -> 87/sqrt(5.91)*ln(1.196/0.3148) = 47.8+r = H.run('impedance', { geom: 'microstrip', mode: 'impedance', w: '0.35', h: '0.2', oz: '1', er: '4.5' }); check('microstrip Z0', o(r, 'Impedance'), 47.8, 0.01);+r = H.run('impedance', { geom: 'microstrip', mode: 'width', Z: '47.8', h: '0.2', oz: '1', er: '4.5' }); check('microstrip inverse', o(r, 'Trace width'), 0.35, 0.01);+r = H.run('ldo', { Vin: '5', Vout: '3.3', Iout: '300m', Iq: '0', theta: '184', Ta: '25', Tjmax: '125' }); check('ldo Pd', o(r, 'Dissipation'), 0.51); check('ldo Tj', o(r, 'Junction'), 118.84);+r = H.run('buck', { Vin: '12', Vout: '3.3', Iout: '2', fsw: '500k', rip: '30', eff: '90' }); check('buck L', o(r, 'Minimum inductance'), 3.3 * 8.7 / (0.6 * 500e3 * 12));+r = H.run('boost', { Vin: '3.3', Vout: '12', Iout: '0.5', fsw: '600k', rip: '30', eff: '85' }); check('boost D', o(r, 'Duty'), (1 - 3.3 * 0.85 / 12) * 100);+r = H.run('holdup', { mode: 'capacitance', load: 'constant power', P: '2', V1: '12', V2: '9', t: '10m' }); check('holdup C', o(r, 'Required'), 2 * 2 * 0.01 / (144 - 81));+r = H.run('battery', { cap: '2000', Ia: '25m', Is: '15u', duty: '2', derate: '85' }); check('battery h', o(r, 'Battery life'), 2 * 0.85 / (0.025 * 0.02 + 15e-6 * 0.98));+// UM10204: Fm, 3.3 V, 200 pF -> Rmax 1770, Rmin 967+r = H.run('i2c', { VDD: '3.3', Cb: '200p', speed: 'Fast 400 kHz' }); check('i2c Rmax', o(r, 'Maximum'), 1770, 0.005); check('i2c Rmin', o(r, 'Minimum'), 966.7, 0.005);+r = H.run('crystal', { CL: '12p', Cs: '4p', series: 'E12' }); check('xtal C', o(r, 'Exact'), 16e-12);+// AN2867 Rev 10 §3.3 example: CL 15 pF, Cs 5 pF -> C1 = C2 = 20 pF+r = H.run('crystal', { CL: '15p', Cs: '5p', series: 'E24' }); check('xtal AN2867 C1=C2', o(r, 'Exact'), 20e-12); check('xtal E24 20p', o(r, 'Nearest'), 20e-12);+r = H.run('crystal', { mode: 'CL from C1/C2', CL: '15p', Cs: '5p', C1: '20p', C2: '20p' }); check('xtal CL from caps', o(r, 'Load the crystal'), 15e-12);+r = H.run('crystal', { mode: 'CL from C1/C2', CL: '10p', Cs: '3p', C1: '10p', C2: '22p' }); check('xtal asym CL', o(r, 'Load the crystal'), 10e-12 * 22e-12 / 32e-12 + 3e-12);+// AN2867 Rev 10 §3.4 example: 8 MHz, C0 7 pF, CL 10 pF, ESR 80 Ω -> gm_crit 0.23 mA/V; gm 25 mA/V -> margin ~107+r = H.run('crystal', { CL: '10p', Cs: '5p', F: '8M', C0: '7p', ESR: '80', gm: '25m' });+check('xtal gm_crit', o(r, 'gm_crit'), 4 * 80 * Math.pow(2 * Math.PI * 8e6, 2) * Math.pow(17e-12, 2)); check('xtal gm_crit ~0.23 mA/V', o(r, 'gm_crit'), 0.23e-3, 0.02);+check('xtal gain margin ~107', o(r, 'Gain margin'), 107, 0.01);+r = H.run('crystal', { CL: '10p', Cs: '5p', F: '8M', C0: '7p', ESR: '80', gm: '1m' }); check('xtal low margin warns', r.warnings.length, 1);+// trim sensitivity: C0 5 pF, Cm 10 fF -> -22.22 ppm/pF at CL 10 pF (CL = 10p exactly: E12 10p caps with Cs 5p give 10p)+r = H.run('crystal', { CL: '10p', Cs: '5p', series: 'E12', C0: '5p', Cm: '10f' }); check('xtal TS', o(r, 'Trim sensitivity'), -22.222); check('xtal zero offset', o(r, 'Frequency offset') + 1, 1);+r = H.run('crystal', { mode: 'CL from C1/C2', CL: '12p', Cs: '4p', C1: '12p', C2: '12p', C0: '5p', Cm: '10f' });+check('xtal pull offset', o(r, 'Frequency offset'), (10e-15 / (2 * 15e-12) - 10e-15 / (2 * 17e-12)) * 1e6);+// drive level AN2867 §3.5.2: IQ = 2πF·Vrms·(C1 + Cs/2 + Cprobe), DL = ESR·IQ²+r = H.run('crystal', { CL: '15p', Cs: '5p', series: 'E24', F: '8M', ESR: '80', Vpp: '1', Cp: '1p', DLmax: '1m' });+{ const IQ = 2 * Math.PI * 8e6 * (1 / (2 * Math.SQRT2)) * 23.5e-12; check('xtal IQ', o(r, 'Crystal current'), IQ); check('xtal DL', o(r, 'Drive level'), 80 * IQ * IQ);+ check('xtal DL ~13.95 uW', o(r, 'Drive level'), 13.95e-6, 0.005); check('xtal IQmaxPP', o(r, 'Max IQ'), 2 * Math.SQRT2 * Math.sqrt(1e-3 / 80)); }+r = H.run('shunt', { I: '10', R: '5m', G: '50', bits: '12', Vref: '3.3' }); check('shunt P', o(r, 'Shunt'), 0.5);+r = H.run('adc', { bits: '12', Vref: '3.3', Vin: '1.65' }); check('adc code', o(r, 'Code'), 2048); check('adc SNR', o(r, 'Ideal SNR'), 74.0);+r = H.run('thermal', { mode: 'required heatsink', P: '5', Ta: '40', jc: '1.5', cs: '0.5', Tj: '125' }); check('heatsink', o(r, 'Heatsink'), 15);+// AWG 24: 0.511 mm, 84.2 mΩ/m+r = H.run('wire', { awg: '24', len: '1', I: '1', rt: 'no', T: '20' }); check('awg24 d', o(r, 'Diameter'), 0.511, 0.003); check('awg24 R/m', o(r, 'Resistance per metre'), 0.0842, 0.005);+r = H.run('rf', { val: '0', unit: 'dBm', Z: '50' }); check('0 dBm Vrms', o(r, 'RMS'), 0.2236);+r = H.run('wavelength', { f: '2.4G', er: '1' }); check('2.4G λ', o(r, 'Wavelength'), 124.91, 0.001);+r = H.run('eseries', { val: '4k8', series: 'E96' }); check('E96 4.8k', o(r, 'Nearest'), 4750);+// full published IEC 60063 E96 table+const E96 = '100 102 105 107 110 113 115 118 121 124 127 130 133 137 140 143 147 150 154 158 162 165 169 174 178 182 187 191 196 200 205 210 215 221 226 232 237 243 249 255 261 267 274 280 287 294 301 309 316 324 332 340 348 357 365 374 383 392 402 412 422 432 442 453 464 475 487 499 511 523 536 549 562 576 590 604 619 634 649 665 681 698 715 732 750 768 787 806 825 845 866 887 909 931 953 976'.split(' ').map(Number);+check('E96 table matches IEC 60063', H.E_BASE.E96.map(x => Math.round(x * 100)).join(), E96.join());++// ---- expansion 2026-09-25+// IPC-2152 baseline fit (smps.us): 1 A, 10 °C -> A = 117.555*10^-0.913 + 1.15 = 15.52 mil² -> 11.33 mil at 1 oz (34.79 µm)+r = H.run('trace', { mode: 'width', I: '1', dT: '10', oz: '1', len: '50' }); check('IPC-2152 fit 1A', o(r, 'Width'), 15.52 / (34.79 / 25.4), 0.005);+r = H.run('trace', { mode: 'current', w: String(15.52 / (34.79 / 25.4) * 0.0254), dT: '10', oz: '1' }); check('IPC-2152 inverse', o(r, 'Maximum current'), 1, 0.005);+// IPC-2221B Table 6-1 (two independent reproductions): B2 1000 V = 5.0, B4 1000 V = 2.325, B1 48 V = 0.1+r = H.run('spacing', { V: '1000', col: 'B2 external, uncoated (sea level – 3050 m)' }); check('spacing B2 1kV', o(r, 'Minimum spacing'), 5.0);+r = H.run('spacing', { V: '1000', col: 'B4 external, with permanent polymer coating / solder mask' }); check('spacing B4 1kV', o(r, 'Minimum spacing'), 2.325);+r = H.run('spacing', { V: '48', col: 'B1 internal layer' }); check('spacing B1 48V', o(r, 'Minimum spacing'), 0.1);+r = H.run('spacing', { V: '300', col: 'B2 external, uncoated (sea level – 3050 m)' }); check('spacing B2 300V', o(r, 'Minimum spacing'), 1.25);+r = H.run('diffpair', { geom: 'microstrip', w: '0.15', s: '0.15', h: '0.1', oz: '0.5', er: '4.3' }); check('diffpair Zdiff', o(r, 'Differential'), 94.9, 0.01);+r = H.run('attenuator', { dB: '6', Z: '50' }); check('6dB pi shunt', o(r, 'Pi: shunt'), 150.5, 0.002); check('6dB pi series', o(r, 'Pi: series'), 37.35, 0.002);+r = H.run('vswr', { val: '1.5', kind: 'VSWR', Z0: '50' }); check('VSWR1.5 RL', o(r, 'Return loss'), 13.98, 0.002); check('VSWR1.5 ML', o(r, 'Mismatch'), 0.177, 0.01);+r = H.run('timer555', { mode: 'astable', RA: '1k', RB: '10k', C: '10n' }); check('555 f', o(r, 'Frequency'), 1.44 / (21e3 * 10e-9));+r = H.run('regulator', { mode: 'R2 for target Vout', Vref: '1.25', Iadj: '50u', R1: '240', Vout: '5', series: 'E96' }); check('LM317 R2', o(r, 'Exact R2'), 3.75 / (1.25 / 240 + 50e-6));+r = H.run('ntc', { mode: 'resistance at temperature', R25: '10k', B: '3435', T: '25' }); check('NTC R25', o(r, 'Resistance'), 10000);+r = H.run('ntc', { mode: 'resistance at temperature', R25: '10k', B: '3435', T: '60' }); check('NTC 60C', o(r, 'Resistance'), 2981, 0.005);+r = H.run('ntc', { mode: 'temperature from resistance', R25: '10k', B: '3435', R: '2981' }); check('NTC inverse', o(r, 'Temperature'), 60, 0.005);+r = H.run('skin', { f: '100M', mat: 'copper' }); check('skin 100MHz', o(r, 'Skin depth'), 6.6, 0.01);+r = H.run('via', { d: '0.3', tp: '25', h: '1.6', pad: '0.6', anti: '1.0', er: '4.3', dT: '10', Z0: '50' }); check('via R', o(r, 'DC resistance'), 1.724e-8 * 0.0016 / (Math.PI * (0.175 ** 2 - 0.15 ** 2) * 1e-6)); check('via L', o(r, 'Inductance'), 1.30e-9, 0.01);+r = H.run('fusing', { shape: 'PCB trace', w: '0.25', oz: '1', t: '1', Ta: '25' }); check('Onderdonk', o(r, 'Fusing'), 17.17 * Math.sqrt(Math.log10(1 + 1058 / 259) / 33), 0.005);+r = H.run('rfind', { target: '3k57', series: 'E24', cfg: 'series or parallel' }); check('rfind <0.3%', Math.abs(o(r, 'Error')) < 0.3 ? 1 : 0, 1);+r = H.run('spiral', { shape: 'square', n: '5', dout: '5', din: '2' }); check('spiral L', o(r, 'Inductance'), 118.1e-9, 0.005);+r = H.run('bandwidth', { tr: '1n', er: '3.3', len: '100' }); check('BW 1ns', o(r, '−3 dB'), 350e6);+r = H.run('combine', { kind: 'resistors', cfg: 'parallel', list: '10k, 10k' }); check('R par', o(r, 'Equivalent'), 5000);+r = H.run('combine', { kind: 'capacitors', cfg: 'series', list: '10n, 10n' }); check('C ser', o(r, 'Equivalent'), 5e-9);+r = H.run('opamp', { cfg: 'non-inverting', Rf: '10k', Rg: '1k', gbw: '10M', sr: '10M', Vpk: '2' }); check('opamp G', o(r, 'Gain'), 11); check('opamp BW', o(r, 'Small-signal'), 10e6 / 11);+r = H.run('pdn', { V: '1', rip: '3', dI: '5', fmax: '100M' }); check('PDN Z', o(r, 'Target'), 0.006);+r = H.run('mosfet', { V: '24', I: '5', Rds: '10m', kT: '1.5', D: '50', fsw: '100k', tr: '20n', tf: '20n', Qg: '30n', Vgs: '10' }); check('mosfet Pc', o(r, 'Conduction'), 0.1875); check('mosfet Psw', o(r, 'Switching'), 0.5 * 24 * 5 * 40e-9 * 1e5);+r = H.run('ppm', { f: '32.768k', ppm: '20' }); check('ppm drift/day', o(r, 'Clock drift per day'), 1.728);+r = H.run('units', { val: '10', u: 'mil' }); check('10 mil', o(r, 'mm'), 0.254);+for (const c of H.CALCS) { const rr = H.run(c.id, {}); if (!rr.ok) { n++; fail++; console.log('FAIL defaults of', c.id, rr.error); } else n++; }+++// schematics: every drawing renders for the defaults and for every option of every select input+{ const S = require('./schematics.js'); let n = 0, bad = [];+ for (const id of S.ids) { const c = H.CALCS.find(x => x.id === id); if (!c) { bad.push(id + ' (no calc)'); continue; }+ const variants = [{}]; for (const f of c.inputs) if (f.type === 'select') for (const opt of f.options) variants.push({ [f.key]: opt });+ for (const v of variants) { const svg = S.draw(id, v); n++; if (!svg || !svg.startsWith('<svg') || /undefined|NaN/.test(svg)) bad.push(id + ' ' + JSON.stringify(v)); } }+ check(`schematics render (${n} variants, ${S.ids.length} drawings)`, bad.length, 0); if (bad.length) console.log(' bad:', bad.join('; ')); }+console.log(`${n - fail}/${n} checks passed`); process.exit(fail ? 1 : 0);
uninstall.shadded+8@@ -0,0 +1,8 @@+#!/bin/bash+set -euo pipefail+for p in $(ls "${HOME}/.adom/instances/hwcalc/"*.json 2>/dev/null); do+ pid=$(node -e "try{console.log(require('$p').pid||'')}catch{}"); [ -n "$pid" ] && kill "$pid" 2>/dev/null || true+done+rm -f "${HOME}/.local/bin/hwcalc"+rm -rf "${HOME}/.claude/skills/hwcalc"+echo "Removed Hardware Calculator (settings kept in ~/.adom/instances/hwcalc)"