From 8c4d60f5a2bd388a07f3c3c7e84a2602e4179a2a Mon Sep 17 00:00:00 2001 From: kim Date: Sun, 4 Oct 2026 10:47:34 +0900 Subject: [PATCH] =?UTF-8?q?feat(pcb):=20PCB=20=EC=A0=9C=EC=9E=91=20?= =?UTF-8?q?=EC=95=B1=20=E2=80=94=20=EB=B6=80=ED=92=88=20=EB=B0=B0=EC=B9=98?= =?UTF-8?q?=C2=B7=ED=95=80=20=EC=97=B0=EA=B2=B0=20=EC=97=90=EB=94=94?= =?UTF-8?q?=ED=84=B0,=20Freerouting=20=ED=97=A4=EB=93=9C=EB=A6=AC=EC=8A=A4?= =?UTF-8?q?=20=EC=9E=90=EB=8F=99=EB=B0=B0=EC=84=A0(DSN/SES),=20=EA=B2=A9?= =?UTF-8?q?=EB=A6=AC=20=EA=B0=80=EA=B3=B5=C2=B7=EB=93=9C=EB=A6=B4=C2=B7?= =?UTF-8?q?=EC=99=B8=EA=B3=BD=20=EB=B0=80=EB=A7=81=20G-code=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1(clipper-lib),=20=EC=B0=BD=EC=9E=91=20=EB=A9=94?= =?UTF-8?q?=EB=89=B4=EC=97=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 3 + package-lock.json | 6 + package.json | 1 + scripts/install-freerouting.sh | 10 + src/gateway/routes/routes-pcb.ts | 62 +++++ src/gateway/server.ts | 2 + src/tools/pcb/dsn.ts | 152 ++++++++++++ src/tools/pcb/footprints.ts | 107 +++++++++ src/tools/pcb/freerouting.ts | 65 +++++ src/tools/pcb/gcode.ts | 196 +++++++++++++++ src/tools/pcb/types.ts | 37 +++ web-ui/html/index.html | 1 + web-ui/html/pcb-app.html | 397 +++++++++++++++++++++++++++++++ 13 files changed, 1039 insertions(+) create mode 100755 scripts/install-freerouting.sh create mode 100644 src/gateway/routes/routes-pcb.ts create mode 100644 src/tools/pcb/dsn.ts create mode 100644 src/tools/pcb/footprints.ts create mode 100644 src/tools/pcb/freerouting.ts create mode 100644 src/tools/pcb/gcode.ts create mode 100644 src/tools/pcb/types.ts create mode 100644 web-ui/html/pcb-app.html diff --git a/.gitignore b/.gitignore index a23711f..971bfc4 100644 --- a/.gitignore +++ b/.gitignore @@ -182,3 +182,6 @@ voicepack_ko/ /*key*.txt /*token*.txt /*secret*.txt + +# --- 외부 도구 바이너리(Freerouting jar 등, scripts/install-freerouting.sh 로 설치) --- +.smallclaw/tools/ diff --git a/package-lock.json b/package-lock.json index 0d9eaa4..591358c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "avr8js": "^0.21.0", "better-sqlite3": "^12.9.0", "chromadb": "^3.5.0", + "clipper-lib": "^6.4.2", "commander": "^14.0.3", "cors": "^2.8.6", "croner": "^10.0.1", @@ -1289,6 +1290,11 @@ "node": ">= 10" } }, + "node_modules/clipper-lib": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/clipper-lib/-/clipper-lib-6.4.2.tgz", + "integrity": "sha512-knglhjQX5ihNj/XCIs6zCHrTemdvHY3LPZP9XB2nq2/3igyYMFueFXtfp84baJvEE+f8pO1ZS4UVeEgmLnAprQ==" + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", diff --git a/package.json b/package.json index 1c5ec72..ee9f4ac 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "avr8js": "^0.21.0", "better-sqlite3": "^12.9.0", "chromadb": "^3.5.0", + "clipper-lib": "^6.4.2", "commander": "^14.0.3", "cors": "^2.8.6", "croner": "^10.0.1", diff --git a/scripts/install-freerouting.sh b/scripts/install-freerouting.sh new file mode 100755 index 0000000..e92c52b --- /dev/null +++ b/scripts/install-freerouting.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PCB 앱의 자동배선기(Freerouting)를 .smallclaw/tools/freerouting/ 에 설치한다. +# 사용: scripts/install-freerouting.sh [버전] (기본 2.4.1, Java 21+ 필요) +set -euo pipefail +VER="${1:-2.4.1}" +DIR="$(cd "$(dirname "$0")/.." && pwd)/.smallclaw/tools/freerouting" +mkdir -p "$DIR" +curl -fL -o "$DIR/freerouting-$VER.jar" "https://github.com/freerouting/freerouting/releases/download/v$VER/freerouting-$VER.jar" +ln -sf "freerouting-$VER.jar" "$DIR/freerouting.jar" +echo "installed: $DIR/freerouting-$VER.jar" diff --git a/src/gateway/routes/routes-pcb.ts b/src/gateway/routes/routes-pcb.ts new file mode 100644 index 0000000..c2c9a3a --- /dev/null +++ b/src/gateway/routes/routes-pcb.ts @@ -0,0 +1,62 @@ +import express from 'express'; +import { FOOTPRINTS } from '../../tools/pcb/footprints'; +import { buildDsn, parseSes, validateProject } from '../../tools/pcb/dsn'; +import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting'; +import { buildGcode } from '../../tools/pcb/gcode'; +import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types'; + +function normalize(raw: any): PcbProject { + const p = raw?.project ?? raw ?? {}; + return { + board: { w: Number(p.board?.w), h: Number(p.board?.h) }, + parts: Array.isArray(p.parts) ? p.parts.slice(0, 400).map((x: any) => ({ ref: String(x.ref), fp: String(x.fp), x: Number(x.x), y: Number(x.y), rot: Number(x.rot) || 0, value: x.value ? String(x.value) : undefined })) : [], + nets: Array.isArray(p.nets) ? p.nets.slice(0, 600).map((n: any) => ({ name: String(n.name), pins: Array.isArray(n.pins) ? n.pins.map(String) : [] })) : [], + rules: { ...DEFAULT_RULES, ...(p.rules || {}), layers: p.rules?.layers === 2 ? 2 : 1, copper: p.rules?.copper === 'F.Cu' ? 'F.Cu' : 'B.Cu' }, + mill: p.mill, + }; +} + +export function registerPcbRoutes(app: express.Application, requireGatewayAuth: express.RequestHandler): void { + app.get('/api/pcb/status', requireGatewayAuth, (_req, res) => { + res.json(freeroutingStatus()); + }); + + app.get('/api/pcb/footprints', requireGatewayAuth, (_req, res) => { + res.json({ footprints: FOOTPRINTS }); + }); + + // 자동 배선: 프로젝트 → DSN → Freerouting → SES → 트레이스 + app.post('/api/pcb/route', requireGatewayAuth, async (req, res) => { + try { + const project = normalize(req.body); + const errors = validateProject(project); + if (errors.length) { res.status(400).json({ error: errors[0], errors }); return; } + const run = await runFreerouting(buildDsn(project), { + maxPasses: Number(req.body?.maxPasses) || 30, + timeoutSec: Number(req.body?.timeoutSec) || 120, + }); + const routed = parseSes(run.ses, project); + res.json({ ...routed, stats: { unrouted: run.unrouted, violations: run.violations, seconds: run.seconds }, log: run.log }); + } catch (err: any) { + res.status(500).json({ error: String(err?.message || err) }); + } + }); + + // 밀링 G-code: 프로젝트 + 배선 결과 → 격리/드릴/외곽 파일 + app.post('/api/pcb/gcode', requireGatewayAuth, (req, res) => { + try { + const project = normalize(req.body); + const errors = validateProject(project); + if (errors.length) { res.status(400).json({ error: errors[0], errors }); return; } + const rr = req.body?.routed || {}; + const routed: Routed = { + traces: Array.isArray(rr.traces) ? rr.traces : [], + vias: Array.isArray(rr.vias) ? rr.vias : [], + }; + if (!routed.traces.length) { res.status(400).json({ error: '배선 결과가 없습니다. 먼저 자동 배선을 실행하세요.' }); return; } + res.json(buildGcode(project, routed)); + } catch (err: any) { + res.status(500).json({ error: String(err?.message || err) }); + } + }); +} diff --git a/src/gateway/server.ts b/src/gateway/server.ts index 9e51970..b7bc064 100644 --- a/src/gateway/server.ts +++ b/src/gateway/server.ts @@ -92,6 +92,7 @@ import { registerUserRoutes } from './routes/routes-users'; import { registerDetectiveRoutes } from './routes/routes-detective'; import { registerPptxRoutes } from './routes/routes-pptx'; import { registerDentalJournalRoutes } from './routes/routes-dental-journals'; +import { registerPcbRoutes } from './routes/routes-pcb'; import { registerVoiceRoutes } from './routes/routes-voice'; import { registerVoiceRealtimeRoutes, attachVoiceRealtimeWsProxy } from './routes/routes-voice-realtime'; import { registerMusicRoutes } from './routes/routes-music'; @@ -3062,6 +3063,7 @@ app.get('/api/files/{*filePath}', (req: express.Request, res: express.Response) registerPptxRoutes(app, getSessionUser, requireGatewayAuth, imageSearch); registerDentalJournalRoutes(app, requireGatewayAuth); +registerPcbRoutes(app, requireGatewayAuth); diff --git a/src/tools/pcb/dsn.ts b/src/tools/pcb/dsn.ts new file mode 100644 index 0000000..f4265be --- /dev/null +++ b/src/tools/pcb/dsn.ts @@ -0,0 +1,152 @@ +// 프로젝트 → Specctra DSN(Freerouting 입력), SES(Freerouting 출력) → 트레이스. +// 단위: DSN 은 um(정수), 에디터는 mm. DSN 은 y 가 위로 증가하므로 y 를 뒤집는다. +// 회전은 DSN 에 맡기지 않고 부품 인스턴스마다 이미 회전된 핀 좌표로 image 를 만든다(회전 의미 불일치 방지). +import { FOOTPRINT_MAP, placedPads } from './footprints'; +import type { PcbProject, Routed, Trace, Via } from './types'; + +const um = (mm: number) => Math.round(mm * 1000); +const safe = (s: string) => String(s).replace(/[^A-Za-z0-9_+\-.]/g, '_'); + +export function validateProject(p: PcbProject): string[] { + const errs: string[] = []; + if (!(p.board?.w > 5 && p.board?.h > 5)) errs.push('보드 크기가 너무 작습니다.'); + const refs = new Set(); + for (const part of p.parts) { + if (!FOOTPRINT_MAP.has(part.fp)) errs.push(`알 수 없는 풋프린트: ${part.fp} (${part.ref})`); + if (refs.has(part.ref)) errs.push(`부품 번호 중복: ${part.ref}`); + refs.add(part.ref); + } + const pads = placedPads(p.parts); + const padIds = new Set(pads.map(x => x.id)); + const margin = 0.5; + for (const pad of pads) { + if (pad.x - pad.w / 2 < margin || pad.y - pad.h / 2 < margin || pad.x + pad.w / 2 > p.board.w - margin || pad.y + pad.h / 2 > p.board.h - margin) { + errs.push(`${pad.id} 패드가 보드 가장자리(${margin}mm)에 너무 가깝거나 밖에 있습니다.`); + } + } + for (const n of p.nets) for (const pin of n.pins) if (!padIds.has(pin)) errs.push(`넷 ${n.name}: 존재하지 않는 핀 ${pin}`); + if (p.rules.layers === 1 && p.rules.copper === 'B.Cu' && pads.some(x => x.smd)) errs.push('아랫면(B.Cu) 단면 보드에는 SMD 부품을 쓸 수 없습니다. 윗면(F.Cu)을 고르거나 SMD를 빼세요.'); + if (p.nets.filter(n => n.pins.length >= 2).length === 0) errs.push('2핀 이상 연결된 넷이 없습니다.'); + return errs; +} + +export function layerNames(p: PcbProject): string[] { + return p.rules.layers === 2 ? ['F.Cu', 'B.Cu'] : [p.rules.copper]; +} + +export function buildDsn(p: PcbProject): string { + const layers = layerNames(p); + const pads = placedPads(p.parts); + const L: string[] = []; + L.push('(pcb homeclaw.dsn'); + L.push(' (parser (string_quote ") (space_in_quoted_tokens on) (host_cad "homeclaw") (host_version "1"))'); + L.push(' (resolution um 10)'); + L.push(' (unit um)'); + L.push(' (structure'); + layers.forEach((l, i) => L.push(` (layer ${l} (type signal) (property (index ${i})))`)); + const W = um(p.board.w), H = um(p.board.h); + L.push(` (boundary (path pcb 0 0 0 0 ${-H} ${W} ${-H} ${W} 0 0 0))`); + const viaName = `Via[0-1]_${um(p.rules.viaDia)}:${um(p.rules.viaDrill)}_um`; + // 단면 보드에도 비아 정의가 필요하다(없으면 Freerouting 이 viaRule null NPE 로 배선을 시작도 못 함). + L.push(` (via "${viaName}")`); + L.push(` (rule (width ${um(p.rules.trace)}) (clearance ${um(p.rules.clearance)}) (clearance ${um(p.rules.clearance)} (type default_smd)))`); + L.push(' )'); + + // placement + library(image/padstack) + const padstacks = new Map(); // key → 정의 + const psName = (pad: typeof pads[number]) => { + const key = `${pad.shape}_${um(pad.w)}x${um(pad.h)}${pad.smd ? '_smd' : ''}`; + if (!padstacks.has(key)) { + const onLayers = pad.smd ? ['F.Cu'].filter(l => layers.includes(l)) : layers; + const shapes = onLayers.map(l => { + if (pad.shape === 'circle' || Math.abs(pad.w - pad.h) < 1e-6 && pad.shape !== 'rect') return ` (shape (circle ${l} ${um(pad.w)} 0 0))`; + if (pad.shape === 'oval') { + const horiz = pad.w >= pad.h, len = Math.abs(pad.w - pad.h) / 2, wd = Math.min(pad.w, pad.h); + return horiz ? ` (shape (path ${l} ${um(wd)} ${-um(len)} 0 ${um(len)} 0))` : ` (shape (path ${l} ${um(wd)} 0 ${-um(len)} 0 ${um(len)}))`; + } + return ` (shape (rect ${l} ${-um(pad.w / 2)} ${-um(pad.h / 2)} ${um(pad.w / 2)} ${um(pad.h / 2)}))`; + }); + padstacks.set(key, ` (padstack ${key}\n${shapes.join('\n')}\n (attach off)\n )`); + } + return key; + }; + L.push(' (placement'); + for (const part of p.parts) L.push(` (component IMG_${safe(part.ref)} (place ${safe(part.ref)} ${um(part.x)} ${-um(part.y)} front 0))`); + L.push(' )'); + L.push(' (library'); + for (const part of p.parts) { + L.push(` (image IMG_${safe(part.ref)}`); + for (const pad of pads.filter(x => x.ref === part.ref)) { + L.push(` (pin ${psName(pad)} ${safe(pad.n)} ${um(pad.x - part.x)} ${-um(pad.y - part.y)})`); + } + L.push(' )'); + } + for (const def of padstacks.values()) L.push(def); + { + const shapes = layers.map(l => ` (shape (circle ${l} ${um(p.rules.viaDia)} 0 0))`).join('\n'); + L.push(` (padstack "${viaName}"\n${shapes}\n (attach off)\n )`); + } + L.push(' )'); + + // network + L.push(' (network'); + const nets = p.nets.filter(n => n.pins.length >= 2); + const netName = new Map(); + nets.forEach((n, i) => netName.set(n.name, safe(n.name) || `N${i}`)); + for (const n of nets) { + const pins = n.pins.map(id => { const k = id.lastIndexOf('-'); return `${safe(id.slice(0, k))}-${safe(id.slice(k + 1))}`; }); + L.push(` (net ${netName.get(n.name)} (pins ${pins.join(' ')}))`); + } + const via = ` (circuit (use_via "${viaName}"))`; + L.push(` (class default ${nets.map(n => netName.get(n.name)).join(' ')}${via} (rule (width ${um(p.rules.trace)}) (clearance ${um(p.rules.clearance)})))`); + L.push(' )'); + L.push(' (wiring)'); + L.push(')'); + return L.join('\n') + '\n'; +} + +// ── SES 파서 ───────────────────────────────────────────────────────────────── +type Node = string | Node[]; +function parseSexp(src: string): Node { + const tok = src.match(/"[^"]*"|\(|\)|[^\s()]+/g) || []; + let i = 0; + const read = (): Node => { + const t = tok[i++]; + if (t === '(') { const arr: Node[] = []; while (i < tok.length && tok[i] !== ')') arr.push(read()); i++; return arr; } + return t.startsWith('"') ? t.slice(1, -1) : t; + }; + return read(); +} +const head = (n: Node) => (Array.isArray(n) && typeof n[0] === 'string' ? n[0] : ''); + +export function parseSes(ses: string, p: PcbProject): Routed { + const root = parseSexp(ses) as Node[]; + const routes = root.find(n => head(n) === 'routes') as Node[] | undefined; + if (!routes) throw new Error('SES 에 routes 가 없습니다.'); + const res = routes.find(n => head(n) === 'resolution') as string[] | undefined; + const perUm = res ? Number(res[2]) : 10; // "resolution um 10" → 10 단위 = 1um + const toMm = (v: string) => Number(v) / perUm / 1000; + const traces: Trace[] = [], vias: Via[] = []; + const netOut = routes.find(n => head(n) === 'network_out') as Node[] | undefined; + for (const net of (netOut || []).filter(n => head(n) === 'net') as Node[][]) { + const name = String(net[1]); + for (const item of net.slice(2)) { + if (head(item) === 'wire') { + const path = (item as Node[]).find(n => head(n) === 'path') as string[] | undefined; + if (!path) continue; + const coords = path.slice(3).map(Number); + const pts: [number, number][] = []; + for (let k = 0; k + 1 < coords.length; k += 2) pts.push([coords[k] / perUm / 1000, -coords[k + 1] / perUm / 1000]); + traces.push({ net: name, layer: path[1], w: toMm(path[2]), pts }); + } else if (head(item) === 'via') { + const v = item as string[]; + vias.push({ net: name, x: toMm(v[2]), y: -toMm(v[3]) }); + } + } + } + // 원래 이름으로 되돌리기(safe() 로 바뀐 경우 대비) + const back = new Map(p.nets.map(n => [safe(n.name), n.name])); + traces.forEach(t => { t.net = back.get(t.net) || t.net; }); + vias.forEach(v => { v.net = back.get(v.net) || v.net; }); + return { traces, vias }; +} diff --git a/src/tools/pcb/footprints.ts b/src/tools/pcb/footprints.ts new file mode 100644 index 0000000..9b21808 --- /dev/null +++ b/src/tools/pcb/footprints.ts @@ -0,0 +1,107 @@ +// PCB 앱 풋프린트 라이브러리 + 부품 배치 좌표 변환. +// 좌표계: mm, 에디터 좌표(원점 좌상단, y 아래로 증가). 풋프린트 원점은 1번 핀(또는 중심). +// rot 은 시계 방향(화면 기준) 0/90/180/270. 클라이언트 JS(pcb-app.html)에 같은 변환이 있으니 함께 고칠 것. + +export interface Pad { n: string; x: number; y: number; w: number; h: number; shape: 'circle' | 'rect' | 'oval'; drill: number } +export interface Footprint { + id: string; name: string; group: string; smd: boolean; + pads: Pad[]; + body: { x0: number; y0: number; x1: number; y1: number }; // 실크/외곽선 그리기용 +} +export interface PartInst { ref: string; fp: string; x: number; y: number; rot: number; value?: string } +export interface PlacedPad { ref: string; n: string; id: string; x: number; y: number; w: number; h: number; shape: Pad['shape']; drill: number; smd: boolean } + +const round = (v: number) => Math.round(v * 1000) / 1000; + +function tht(n: string | number, x: number, y: number, d: number, drill: number, first = false): Pad { + return { n: String(n), x: round(x), y: round(y), w: d, h: d, shape: first ? 'rect' : 'circle', drill }; +} +function smd(n: string | number, x: number, y: number, w: number, h: number): Pad { + return { n: String(n), x: round(x), y: round(y), w, h, shape: 'rect', drill: 0 }; +} +function bodyOf(pads: Pad[], pad = 0.8) { + const xs = pads.flatMap(p => [p.x - p.w / 2, p.x + p.w / 2]); + const ys = pads.flatMap(p => [p.y - p.h / 2, p.y + p.h / 2]); + return { x0: round(Math.min(...xs) - pad / 2), y0: round(Math.min(...ys) - pad / 2), x1: round(Math.max(...xs) + pad / 2), y1: round(Math.max(...ys) + pad / 2) }; +} +function fp(id: string, name: string, group: string, pads: Pad[], isSmd = false, body?: Footprint['body']): Footprint { + return { id, name, group, smd: isSmd, pads, body: body ?? bodyOf(pads) }; +} + +export function buildFootprints(): Footprint[] { + const list: Footprint[] = []; + // 핀헤더 1xN, 2xN (2.54mm) + for (let n = 2; n <= 10; n++) { + const pads = Array.from({ length: n }, (_, i) => tht(i + 1, 0, i * 2.54, 1.8, 1.0, i === 0)); + list.push(fp(`HDR-1x${n}`, `핀헤더 1x${n}`, '커넥터', pads)); + } + for (const n of [3, 4, 5, 8]) { + const pads: Pad[] = []; + for (let r = 0; r < n; r++) for (let c = 0; c < 2; c++) pads.push(tht(r * 2 + c + 1, c * 2.54, r * 2.54, 1.8, 1.0, r === 0 && c === 0)); + list.push(fp(`HDR-2x${n}`, `핀헤더 2x${n}`, '커넥터', pads)); + } + list.push(fp('TERM-2P', '스크류 터미널 2P (5.08)', '커넥터', [tht(1, 0, 0, 2.4, 1.3, true), tht(2, 5.08, 0, 2.4, 1.3)])); + list.push(fp('TERM-3P', '스크류 터미널 3P (5.08)', '커넥터', [tht(1, 0, 0, 2.4, 1.3, true), tht(2, 5.08, 0, 2.4, 1.3), tht(3, 10.16, 0, 2.4, 1.3)])); + // DIP (행 간격 7.62) + for (const n of [8, 14, 16, 18, 20, 28]) { + const half = n / 2, pads: Pad[] = []; + for (let i = 0; i < half; i++) pads.push(tht(i + 1, 0, i * 2.54, 1.6, 0.9, i === 0)); + for (let i = 0; i < half; i++) pads.push(tht(half + i + 1, 7.62, (half - 1 - i) * 2.54, 1.6, 0.9)); + list.push(fp(`DIP-${n}`, `DIP-${n}`, 'IC', pads, false, { x0: 0.9, y0: -1.3, x1: 6.7, y1: (half - 1) * 2.54 + 1.3 })); + } + // 축방향 저항/다이오드 + for (const p of [7.62, 10.16, 12.7]) { + list.push(fp(`RES-AX-${p}`, `저항 축형 ${p}mm`, '수동소자', [tht(1, 0, 0, 1.8, 0.9), tht(2, p, 0, 1.8, 0.9)])); + } + list.push(fp('DIODE-AX-10.16', '다이오드 축형 10.16mm', '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, 10.16, 0, 1.8, 0.9)])); + for (const p of [2.54, 5.08, 7.62]) { + list.push(fp(`CAP-RAD-${p}`, `커패시터 방사형 ${p}mm`, '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, p, 0, 1.8, 0.9)])); + } + list.push(fp('LED-5MM', 'LED 5mm', '수동소자', [tht(1, 0, 0, 1.8, 0.9, true), tht(2, 2.54, 0, 1.8, 0.9)])); + list.push(fp('TO-92', 'TO-92 (3핀)', '트랜지스터', [tht(1, 0, 0, 1.6, 0.9, true), tht(2, 2.54, 0, 1.6, 0.9), tht(3, 5.08, 0, 1.6, 0.9)])); + list.push(fp('TO-220', 'TO-220 (3핀)', '트랜지스터', [tht(1, 0, 0, 2.2, 1.1, true), tht(2, 2.54, 0, 2.2, 1.1), tht(3, 5.08, 0, 2.2, 1.1)])); + // SMD + list.push(fp('R-0805', '0805 (SMD)', 'SMD', [smd(1, 0, 0, 1.0, 1.4), smd(2, 1.9, 0, 1.0, 1.4)], true)); + list.push(fp('R-1206', '1206 (SMD)', 'SMD', [smd(1, 0, 0, 1.2, 1.8), smd(2, 3.0, 0, 1.2, 1.8)], true)); + { + const pads: Pad[] = []; + for (let i = 0; i < 4; i++) pads.push(smd(i + 1, 0, i * 1.27, 1.6, 0.6)); + for (let i = 0; i < 4; i++) pads.push(smd(5 + i, 5.4, (3 - i) * 1.27, 1.6, 0.6)); + list.push(fp('SOIC-8', 'SOIC-8 (SMD)', 'SMD', pads, true, { x0: 1.0, y0: -0.9, x1: 4.4, y1: 4.7 })); + } + list.push(fp('MOUNT-3.2', '고정 구멍 Ø3.2', '기타', [{ n: '1', x: 0, y: 0, w: 6, h: 6, shape: 'circle', drill: 3.2 }])); + return list; +} + +export const FOOTPRINTS: Footprint[] = buildFootprints(); +export const FOOTPRINT_MAP: Map = new Map(FOOTPRINTS.map(f => [f.id, f])); + +/** 회전(시계 방향, y-아래 좌표계). rot 은 90의 배수로 정규화. */ +export function rotPoint(x: number, y: number, rot: number): [number, number] { + const r = ((Math.round(rot / 90) * 90) % 360 + 360) % 360; + switch (r) { + case 90: return [-y, x]; + case 180: return [-x, -y]; + case 270: return [y, -x]; + default: return [x, y]; + } +} + +export function placedPads(parts: PartInst[]): PlacedPad[] { + const out: PlacedPad[] = []; + for (const part of parts) { + const f = FOOTPRINT_MAP.get(part.fp); + if (!f) continue; + const r = ((Math.round(part.rot / 90) * 90) % 360 + 360) % 360; + const swap = r === 90 || r === 270; + for (const p of f.pads) { + const [dx, dy] = rotPoint(p.x, p.y, part.rot); + out.push({ + ref: part.ref, n: p.n, id: `${part.ref}-${p.n}`, + x: round(part.x + dx), y: round(part.y + dy), + w: swap ? p.h : p.w, h: swap ? p.w : p.h, shape: p.shape, drill: p.drill, smd: f.smd, + }); + } + } + return out; +} diff --git a/src/tools/pcb/freerouting.ts b/src/tools/pcb/freerouting.ts new file mode 100644 index 0000000..2e9ac94 --- /dev/null +++ b/src/tools/pcb/freerouting.ts @@ -0,0 +1,65 @@ +// Freerouting(Java) 헤드리스 실행기 — DSN 을 받아 SES 와 배선 통계를 돌려준다. +import { spawn, spawnSync } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; + +const JAR = process.env.FREEROUTING_JAR || path.resolve(__dirname, '../../../.smallclaw/tools/freerouting/freerouting.jar'); + +export function freeroutingStatus(): { installed: boolean; jar: string; java: string | null } { + let java: string | null = null; + try { + const r = spawnSync('java', ['-version'], { encoding: 'utf8', timeout: 5000 }); + const m = String(r.stderr || r.stdout || '').match(/version "([^"]+)"/); + java = m ? m[1] : null; + } catch { /* java 없음 */ } + return { installed: fs.existsSync(JAR), jar: JAR, java }; +} + +let busy = false; + +export interface RouteRun { ses: string; unrouted: number; violations: number; seconds: number; log: string } + +export async function runFreerouting(dsn: string, opts: { maxPasses?: number; timeoutSec?: number } = {}): Promise { + const st = freeroutingStatus(); + if (!st.installed) throw new Error('Freerouting 이 설치되어 있지 않습니다. scripts/install-freerouting.sh 를 실행하세요.'); + if (!st.java) throw new Error('Java 를 찾을 수 없습니다(Java 21 이상 필요).'); + if (busy) throw new Error('다른 자동 배선이 진행 중입니다. 잠시 후 다시 시도하세요.'); + busy = true; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pcb-route-')); + const t0 = Date.now(); + try { + const inFile = path.join(dir, 'board.dsn'), outFile = path.join(dir, 'board.ses'); + fs.writeFileSync(inFile, dsn); + const passes = Math.min(Math.max(opts.maxPasses ?? 30, 1), 100); + const timeoutMs = Math.min(Math.max(opts.timeoutSec ?? 120, 10), 600) * 1000; + const args = ['-Djava.awt.headless=true', '-Xmx1g', '-jar', JAR, '-de', inFile, '-do', outFile, '-mp', String(passes), '-mt', '2']; + // HOME 을 임시 폴더로 돌려 사용자 홈에 freerouting.json/로그가 생기지 않게 한다. + const env = { ...process.env, HOME: dir, XDG_CONFIG_HOME: dir, XDG_STATE_HOME: dir, XDG_DATA_HOME: dir }; + let log = ''; + await new Promise((resolve, reject) => { + const child = spawn('java', args, { cwd: dir, env }); + const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`자동 배선 시간 초과(${timeoutMs / 1000}초) — 보드를 단순화하거나 패스 수를 줄여 보세요.`)); }, timeoutMs); + child.stdout.on('data', d => { log += d; }); + child.stderr.on('data', d => { log += d; }); + child.on('error', e => { clearTimeout(timer); reject(e); }); + child.on('close', () => { clearTimeout(timer); resolve(); }); + }); + if (!fs.existsSync(outFile)) { + const tail = log.split('\n').filter(Boolean).slice(-4).join(' | ').slice(0, 400); + throw new Error(`Freerouting 이 결과를 만들지 못했습니다: ${tail}`); + } + const all = [...log.matchAll(/\((\d+) unrouted and (\d+) violations\)/g)]; + const last = all[all.length - 1]; + return { + ses: fs.readFileSync(outFile, 'utf8'), + unrouted: last ? Number(last[1]) : -1, + violations: last ? Number(last[2]) : -1, + seconds: Math.round((Date.now() - t0) / 100) / 10, + log: log.split('\n').filter(l => /INFO|WARN|ERROR/.test(l)).slice(-12).join('\n'), + }; + } finally { + busy = false; + fs.rmSync(dir, { recursive: true, force: true }); + } +} diff --git a/src/tools/pcb/gcode.ts b/src/tools/pcb/gcode.ts new file mode 100644 index 0000000..4e01afb --- /dev/null +++ b/src/tools/pcb/gcode.ts @@ -0,0 +1,196 @@ +// 배선 결과 → PCB 밀링 G-code (격리 가공 / 드릴 / 외곽 컷). 도형 연산은 clipper-lib(정수 µm). +// 좌표: 입력은 에디터 mm(좌상단 원점, y 아래로). G-code 는 보드 좌하단 원점, y 위로 → gy = H - y. +// 아랫면 가공(mirror)이면 gx = W - x (보드를 좌우로 뒤집어 동박면을 위로 놓고 깎는다). +import { placedPads } from './footprints'; +import type { MillSettings, PcbProject, Routed } from './types'; +import { DEFAULT_MILL } from './types'; +import { layerNames } from './dsn'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const ClipperLib: any = require('clipper-lib'); +const S = 1000; // mm → µm +type IP = { X: number; Y: number }; +const ip = (x: number, y: number): IP => ({ X: Math.round(x * S), Y: Math.round(y * S) }); + +function circlePoly(cx: number, cy: number, d: number): IP[] { + const n = Math.max(16, Math.min(48, Math.round(d * 12))); + return Array.from({ length: n }, (_, i) => ip(cx + (d / 2) * Math.cos((2 * Math.PI * i) / n), cy + (d / 2) * Math.sin((2 * Math.PI * i) / n))); +} +function rectPoly(cx: number, cy: number, w: number, h: number): IP[] { + return [ip(cx - w / 2, cy - h / 2), ip(cx + w / 2, cy - h / 2), ip(cx + w / 2, cy + h / 2), ip(cx - w / 2, cy + h / 2)]; +} +function offsetOpen(path: IP[], delta: number): IP[][] { + const co = new ClipperLib.ClipperOffset(2, 0.004 * S); + co.AddPath(path, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etOpenRound); + const out: IP[][] = []; + co.Execute(out, delta * S); + return out; +} +function union(polys: IP[][]): IP[][] { + const c = new ClipperLib.Clipper(); + c.AddPaths(polys, ClipperLib.PolyType.ptSubject, true); + const out: IP[][] = []; + c.Execute(ClipperLib.ClipType.ctUnion, out, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero); + return out; +} +function offsetClosed(polys: IP[][], delta: number): IP[][] { + const co = new ClipperLib.ClipperOffset(2, 0.004 * S); + co.AddPaths(polys, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etClosedPolygon); + const out: IP[][] = []; + co.Execute(out, delta * S); + return out; +} +/** 닫힌 윤곽선들(선)을 사각형 영역으로 잘라낸다(보드 밖으로 나가는 가공 제거). */ +function clipLinesToRect(loops: IP[][], x0: number, y0: number, x1: number, y1: number): IP[][] { + const c = new ClipperLib.Clipper(); + c.AddPaths(loops.map(l => [...l, l[0]]), ClipperLib.PolyType.ptSubject, false); + c.AddPath([ip(x0, y0), ip(x1, y0), ip(x1, y1), ip(x0, y1)], ClipperLib.PolyType.ptClip, true); + const tree = new ClipperLib.PolyTree(); + c.Execute(ClipperLib.ClipType.ctIntersection, tree, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero); + return ClipperLib.Clipper.OpenPathsFromPolyTree(tree) as IP[][]; +} + +type Pt = [number, number]; +const toMm = (p: IP): Pt => [p.X / S, p.Y / S]; + +/** 한 층의 동박(패드+비아+트레이스) 합집합. */ +function copperUnion(p: PcbProject, routed: Routed, layer: string): IP[][] { + const polys: IP[][] = []; + for (const pad of placedPads(p.parts)) { + if (pad.smd && layer !== 'F.Cu') continue; + if (pad.shape === 'circle') polys.push(circlePoly(pad.x, pad.y, pad.w)); + else if (pad.shape === 'oval') polys.push(...offsetOpen([ip(pad.x - Math.max(0, pad.w - pad.h) / 2, pad.y), ip(pad.x + Math.max(0, pad.w - pad.h) / 2, pad.y)], Math.min(pad.w, pad.h) / 2)); + else polys.push(rectPoly(pad.x, pad.y, pad.w, pad.h)); + } + for (const v of routed.vias) polys.push(circlePoly(v.x, v.y, p.rules.viaDia)); + for (const t of routed.traces) { + if (t.layer !== layer || t.pts.length < 2) continue; + polys.push(...offsetOpen(t.pts.map(([x, y]) => ip(x, y)), t.w / 2)); + } + return union(polys); +} + +/** 가장 가까운 경로 순서로 재배열(이동 거리 단축). */ +function orderPaths(paths: IP[][]): IP[][] { + const left = paths.filter(pp => pp.length >= 2); + const out: IP[][] = []; + let cur: IP = { X: 0, Y: 0 }; + while (left.length) { + let bi = 0, bd = Infinity; + left.forEach((pp, i) => { const d = (pp[0].X - cur.X) ** 2 + (pp[0].Y - cur.Y) ** 2; if (d < bd) { bd = d; bi = i; } }); + const [pp] = left.splice(bi, 1); + out.push(pp); + cur = pp[pp.length - 1]; + } + return out; +} + +export interface GcodeResult { + files: Record; + preview: { isolation: Record; drills: { x: number; y: number; d: number }[]; outline: Pt[] }; + stats: { holes: number; drillSizes: number[]; isolationLengthMm: number; estMinutes: number }; + warnings: string[]; +} + +export function buildGcode(p: PcbProject, routed: Routed): GcodeResult { + const m: MillSettings = { ...DEFAULT_MILL, ...(p.mill || {}) }; + const W = p.board.w, H = p.board.h; + const warnings: string[] = []; + const layers = layerNames(p); + if (p.rules.clearance < m.toolDia - 1e-9) warnings.push(`최소 간격(${p.rules.clearance}mm)이 가공 폭(${m.toolDia}mm)보다 좁아 일부 배선 사이가 완전히 분리되지 않을 수 있습니다.`); + if (p.rules.trace < m.toolDia) warnings.push(`배선 폭(${p.rules.trace}mm)이 가공 폭(${m.toolDia}mm)보다 가늘어 박리 위험이 있습니다.`); + + const mirrorFor = (layer: string) => (p.rules.layers === 2 ? layer === 'B.Cu' : m.mirror && layer === 'B.Cu'); + const mirrorOthers = p.rules.layers === 1 && m.mirror && p.rules.copper === 'B.Cu'; + const f = (v: number) => (Math.round(v * 1000) / 1000).toString(); + const tx = (x: number, mir: boolean) => f(mir ? W - x : x); + const ty = (y: number) => f(H - y); + + const head = (title: string) => [ + `(${title} — homeclaw PCB)`, + `(board ${W} x ${H} mm, 단위 mm, 원점 = 보드 좌하단${mirrorOthers ? ', 좌우 반전(아랫면 가공)' : ''})`, + 'G21 G90 G17 G94', + m.rpm > 0 ? `M3 S${m.rpm}` : '(스핀들 수동)', + `G0 Z${f(m.safeZ)}`, + ]; + const tail = ['M5', `G0 Z${f(m.safeZ)}`, 'G0 X0 Y0', 'M2']; + + const files: Record = {}; + const isolation: Record = {}; + let isoLen = 0, plunges = 0; + + for (const layer of layers) { + const u = copperUnion(p, routed, layer); + const step = Math.max(m.toolDia * (1 - Math.min(Math.max(m.overlap, 0), 0.9)), 0.02); + let loops: IP[][] = []; + for (let i = 0; i < Math.max(1, Math.round(m.passes)); i++) loops.push(...offsetClosed(u, m.toolDia / 2 + i * step)); + // 보드 밖으로 나가는 부분은 제거(가장자리 0.1mm 안쪽까지만 가공) + const clipped = orderPaths(clipLinesToRect(loops, 0.1, 0.1, W - 0.1, H - 0.1)); + const mir = mirrorFor(layer); + const L = head(`${layer} 격리 가공 (${m.passes}패스, Ø${m.toolDia}mm)`); + isolation[layer] = clipped.map(pp => pp.map(toMm)); + for (const pp of clipped) { + const pts = pp.map(toMm); + L.push(`G0 X${tx(pts[0][0], mir)} Y${ty(pts[0][1])}`); + L.push(`G1 Z${f(m.cutZ)} F${f(m.plunge)}`); + plunges++; + for (let k = 1; k < pts.length; k++) { + L.push(`G1 X${tx(pts[k][0], mir)} Y${ty(pts[k][1])} F${f(m.feed)}`); + isoLen += Math.hypot(pts[k][0] - pts[k - 1][0], pts[k][1] - pts[k - 1][1]); + } + L.push(`G0 Z${f(m.safeZ)}`); + } + L.push(...tail); + files[`copper-${layer === 'F.Cu' ? 'top' : 'bottom'}.nc`] = L.join('\n') + '\n'; + } + + // 드릴 + const holes: { x: number; y: number; d: number }[] = []; + for (const pad of placedPads(p.parts)) if (pad.drill > 0) holes.push({ x: pad.x, y: pad.y, d: pad.drill }); + if (p.rules.layers === 2) for (const v of routed.vias) holes.push({ x: v.x, y: v.y, d: p.rules.viaDrill }); + const sizes = [...new Set(holes.map(h => Math.round(h.d * 100) / 100))].sort((a, b) => a - b); + { + const L = head('드릴'); + for (const sz of sizes) { + L.push(`G0 Z${f(m.safeZ)}`, 'M5', `(공구 교체: Ø${sz}mm 드릴)`, 'M0', m.rpm > 0 ? `M3 S${m.rpm}` : ''); + let pts = holes.filter(h => Math.round(h.d * 100) / 100 === sz).map(h => [ip(h.x, h.y)]); + for (const pp of orderPaths(pts.map(a => [a[0], a[0]]))) { + const [x, y] = toMm(pp[0]); + L.push(`G0 X${tx(x, mirrorOthers)} Y${ty(y)}`, `G1 Z${f(m.drillZ)} F${f(m.plunge)}`, `G0 Z${f(m.safeZ)}`); + } + } + L.push(...tail); + files['drill.nc'] = L.filter(Boolean).join('\n') + '\n'; + } + + // 외곽 컷 (공구 중심은 보드 바깥으로 반지름만큼 오프셋) + const outline: Pt[] = (() => { + const r = offsetClosed([[ip(0, 0), ip(W, 0), ip(W, H), ip(0, H)]], m.outlineDia / 2)[0] || []; + return r.map(toMm); + })(); + { + const L = head(`외곽 컷 (Ø${m.outlineDia}mm)`); + const depthN = Math.max(1, Math.ceil(Math.abs(m.outlineZ) / Math.max(m.outlineStep, 0.1))); + L.push(`G0 X${tx(outline[0][0], mirrorOthers)} Y${ty(outline[0][1])}`); + for (let i = 1; i <= depthN; i++) { + const z = (m.outlineZ * i) / depthN; + L.push(`G1 Z${f(z)} F${f(m.plunge)}`); + for (let k = 1; k < outline.length; k++) L.push(`G1 X${tx(outline[k][0], mirrorOthers)} Y${ty(outline[k][1])} F${f(m.feed)}`); + L.push(`G1 X${tx(outline[0][0], mirrorOthers)} Y${ty(outline[0][1])} F${f(m.feed)}`); + } + L.push(...tail); + files['outline.nc'] = L.join('\n') + '\n'; + } + if (p.rules.layers === 2) warnings.push('양면 보드: 아랫면 파일은 좌우 반전되어 있습니다. 뒤집어 가공할 때 기준 모서리(원점)를 맞춰 정렬하세요.'); + warnings.push('외곽 컷에는 고정 탭이 없습니다. 양면테이프 등으로 기판을 고정하세요.'); + + return { + files, + preview: { isolation, drills: holes, outline }, + stats: { + holes: holes.length, drillSizes: sizes, isolationLengthMm: Math.round(isoLen), + estMinutes: Math.round(((isoLen / Math.max(m.feed, 1)) + plunges * 0.02 + holes.length * 0.03) * 10) / 10, + }, + warnings, + }; +} diff --git a/src/tools/pcb/types.ts b/src/tools/pcb/types.ts new file mode 100644 index 0000000..d525bed --- /dev/null +++ b/src/tools/pcb/types.ts @@ -0,0 +1,37 @@ +import type { PartInst } from './footprints'; + +export interface NetDef { name: string; pins: string[] } // pins: "R1-1" 형식 +export interface PcbRules { + trace: number; // 배선 폭 mm + clearance: number; // 최소 간격 mm + layers: 1 | 2; + copper: 'F.Cu' | 'B.Cu'; // layers===1 일 때 쓰는 동박면 + viaDia: number; viaDrill: number; +} +export interface MillSettings { + toolDia: number; // 격리 가공 유효 절삭폭 mm (V비트면 깊이에서의 폭) + passes: number; // 격리 패스 수 + overlap: number; // 패스 간 겹침 0~0.9 + cutZ: number; // 격리 깊이 (음수) + safeZ: number; + feed: number; plunge: number; rpm: number; + drillZ: number; // 드릴 깊이 (음수, 기판 두께 + 여유) + outlineDia: number; outlineZ: number; outlineStep: number; + mirror: boolean; // 아랫면 가공: 좌우 반전 +} +export interface PcbProject { + board: { w: number; h: number }; + parts: PartInst[]; + nets: NetDef[]; + rules: PcbRules; + mill?: MillSettings; +} +export interface Trace { net: string; layer: string; w: number; pts: [number, number][] } // mm, 에디터 좌표 +export interface Via { net: string; x: number; y: number } +export interface Routed { traces: Trace[]; vias: Via[] } + +export const DEFAULT_RULES: PcbRules = { trace: 0.4, clearance: 0.3, layers: 1, copper: 'B.Cu', viaDia: 0.9, viaDrill: 0.5 }; +export const DEFAULT_MILL: MillSettings = { + toolDia: 0.2, passes: 2, overlap: 0.3, cutZ: -0.1, safeZ: 2, feed: 200, plunge: 60, rpm: 10000, + drillZ: -1.8, outlineDia: 1.0, outlineZ: -1.8, outlineStep: 0.6, mirror: true, +}; diff --git a/web-ui/html/index.html b/web-ui/html/index.html index 55af952..feb7c66 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -69,6 +69,7 @@ + diff --git a/web-ui/html/pcb-app.html b/web-ui/html/pcb-app.html new file mode 100644 index 0000000..7af6173 --- /dev/null +++ b/web-ui/html/pcb-app.html @@ -0,0 +1,397 @@ + + + + + +🔌 PCB 제작 + + + +
+

🔌 PCB 제작

+ + + + + + Freerouting 확인 중… +
+
+ + +
+
+ + + + + + + + + +
+
+
부품을 왼쪽에서 눌러 추가 → 끌어서 배치 → 🔗 핀 연결 모드에서 핀을 차례로 클릭해 연결 → 오른쪽에서 자동 배선
+
+ + +
+ + + +