feat(pcb): 밀링 머신(옥토서버 OctoPrint :5001) 전송 — 상태 조회, G-code 업로드, 확인 후 작업 시작, 일시정지/재개/취소. 관리자 전용, API 키는 서버 금고(관리자가 직접 입력)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
371e1fd9ec
commit
e7dda876ba
4 files changed
+193
-4
No files matched your search
@@ -5,6 +5,7 @@ import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting';
|
||||
import { buildGcode } from '../../tools/pcb/gcode';
|
||||
import { findJumpers, jumperList } from '../../tools/pcb/jumpers';
|
||||
import { simulate, type SimSpec } from '../../tools/pcb/spice';
|
||||
import { jobCommand, millStatus, saveMillKey, startJob, uploadGcode } from '../../tools/pcb/octoprint';
|
||||
import { footprintsByFilter, kicadFootprint, kicadStatus, loadFpIndex, loadSymIndex, searchFootprints, searchSymbols, symbolDetail } from '../../tools/pcb/kicadlib';
|
||||
import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types';
|
||||
|
||||
@@ -19,7 +20,13 @@ function normalize(raw: any): PcbProject {
|
||||
};
|
||||
}
|
||||
|
||||
export function registerPcbRoutes(app: express.Application, requireGatewayAuth: express.RequestHandler): void {
|
||||
export function registerPcbRoutes(app: express.Application, requireGatewayAuth: express.RequestHandler, getSessionUser: (req: express.Request) => any): void {
|
||||
// 실제 기계를 움직이거나 키를 저장하는 요청은 관리자만 허용한다.
|
||||
const requireAdmin: express.RequestHandler = (req, res, next) => {
|
||||
const u = getSessionUser(req);
|
||||
if (!u || u.role !== 'admin') { res.status(403).json({ error: '관리자만 사용할 수 있습니다.' }); return; }
|
||||
next();
|
||||
};
|
||||
app.get('/api/pcb/status', requireGatewayAuth, (_req, res) => {
|
||||
res.json(freeroutingStatus());
|
||||
});
|
||||
@@ -74,6 +81,43 @@ export function registerPcbRoutes(app: express.Application, requireGatewayAuth:
|
||||
}
|
||||
});
|
||||
|
||||
// ── 밀링 머신(옥토서버 OctoPrint :5001, GRBL) ──────────────────────────────
|
||||
app.get('/api/pcb/mill/status', requireGatewayAuth, async (_req, res) => {
|
||||
res.json(await millStatus());
|
||||
});
|
||||
app.post('/api/pcb/mill/key', requireGatewayAuth, requireAdmin, (req, res) => {
|
||||
try { saveMillKey(String(req.body?.key || '').trim()); res.json({ ok: true }); }
|
||||
catch (err: any) { res.status(400).json({ error: String(err?.message || err) }); }
|
||||
});
|
||||
// 업로드만 한다(작업은 시작하지 않음)
|
||||
app.post('/api/pcb/mill/upload', requireGatewayAuth, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const files = req.body?.files && typeof req.body.files === 'object' ? req.body.files as Record<string, string> : {};
|
||||
const done = await uploadGcode(String(req.body?.project || 'board'), files);
|
||||
console.log(`[pcb-mill] upload by ${getSessionUser(req)?.username}: ${done.join(', ')}`);
|
||||
res.json({ uploaded: done });
|
||||
} catch (err: any) { res.status(400).json({ error: String(err?.message || err) }); }
|
||||
});
|
||||
// 작업 시작: 스핀들이 돌기 시작하므로 확인 플래그(confirm:true)가 있어야만 한다
|
||||
app.post('/api/pcb/mill/start', requireGatewayAuth, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
if (req.body?.confirm !== true) { res.status(400).json({ error: '시작 전 확인이 필요합니다(Z 영점, 기판 고정, 공구 확인).' }); return; }
|
||||
const file = String(req.body?.file || '');
|
||||
await startJob(file);
|
||||
console.log(`[pcb-mill] START by ${getSessionUser(req)?.username}: ${file}`);
|
||||
res.json({ ok: true });
|
||||
} catch (err: any) { res.status(400).json({ error: String(err?.message || err) }); }
|
||||
});
|
||||
app.post('/api/pcb/mill/job', requireGatewayAuth, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const cmd = String(req.body?.command || '');
|
||||
if (!['pause', 'resume', 'cancel'].includes(cmd)) { res.status(400).json({ error: 'pause / resume / cancel 만 가능합니다.' }); return; }
|
||||
await jobCommand(cmd as 'pause' | 'resume' | 'cancel');
|
||||
console.log(`[pcb-mill] ${cmd.toUpperCase()} by ${getSessionUser(req)?.username}`);
|
||||
res.json({ ok: true });
|
||||
} catch (err: any) { res.status(400).json({ error: String(err?.message || err) }); }
|
||||
});
|
||||
|
||||
// 회로 시뮬레이션(ngspice): 프로젝트의 부품·넷 → SPICE 넷리스트 → 동작점/시간 응답/주파수 응답
|
||||
app.post('/api/pcb/simulate', requireGatewayAuth, async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -3063,7 +3063,7 @@ app.get('/api/files/{*filePath}', (req: express.Request, res: express.Response)
|
||||
|
||||
registerPptxRoutes(app, getSessionUser, requireGatewayAuth, imageSearch);
|
||||
registerDentalJournalRoutes(app, requireGatewayAuth);
|
||||
registerPcbRoutes(app, requireGatewayAuth);
|
||||
registerPcbRoutes(app, requireGatewayAuth, getSessionUser);
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// 옥토서버(밀링용 OctoPrint :5001, GRBL)로 G-code 업로드/작업 제어.
|
||||
// API 키는 서버 금고(milling.octoprint_key)에만 둔다 — 코드·설정 파일·로그에 남기지 않는다.
|
||||
import { getConfig } from '../../config/config';
|
||||
import { getVault } from '../../security/vault';
|
||||
|
||||
const VAULT_KEY = 'milling.octoprint_key';
|
||||
const DEFAULT_URL = process.env.OCTOPRINT_MILL_URL || 'http://192.168.0.3:5001';
|
||||
|
||||
function baseUrl(): string {
|
||||
const cfg = getConfig().getConfig() as any;
|
||||
return String(cfg?.milling?.octoprint_url || DEFAULT_URL).replace(/\/+$/, '');
|
||||
}
|
||||
function apiKey(): string {
|
||||
if (process.env.OCTOPRINT_MILL_KEY) return process.env.OCTOPRINT_MILL_KEY; // 헤드리스/시험용 선택 경로(금고가 기본)
|
||||
try { const v = getVault(getConfig().getConfigDir()).get(VAULT_KEY, 'pcb:mill'); return v ? v.expose() : ''; } catch { return ''; }
|
||||
}
|
||||
export function saveMillKey(key: string): void {
|
||||
if (!/^[A-Za-z0-9_\-]{16,80}$/.test(key)) throw new Error('API 키 형식이 올바르지 않습니다.');
|
||||
getVault(getConfig().getConfigDir()).set(VAULT_KEY, key, 'pcb:mill-key');
|
||||
}
|
||||
|
||||
async function octo(path: string, init: RequestInit & { json?: unknown } = {}): Promise<{ status: number; body: any }> {
|
||||
const key = apiKey();
|
||||
if (!key) throw new Error('밀링 OctoPrint API 키가 설정되어 있지 않습니다.');
|
||||
const headers: Record<string, string> = { 'X-Api-Key': key, ...(init.headers as Record<string, string> || {}) };
|
||||
let body = init.body;
|
||||
if (init.json !== undefined) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(init.json); }
|
||||
const res = await fetch(baseUrl() + path, { ...init, headers, body, signal: AbortSignal.timeout(10_000) });
|
||||
const text = await res.text();
|
||||
let parsed: any = text; try { parsed = text ? JSON.parse(text) : {}; } catch { /* 본문이 JSON 이 아님 */ }
|
||||
return { status: res.status, body: parsed };
|
||||
}
|
||||
|
||||
export async function millStatus() {
|
||||
let configured = false;
|
||||
try { configured = !!apiKey(); } catch { /* ignore */ }
|
||||
const out: any = { configured, url: baseUrl(), reachable: false };
|
||||
if (!configured) return out;
|
||||
try {
|
||||
const [c, j] = await Promise.all([octo('/api/connection'), octo('/api/job')]);
|
||||
out.reachable = true;
|
||||
if (c.status === 403 || c.status === 401) { out.error = 'API 키가 거부되었습니다. 키를 다시 입력하세요.'; out.reachable = false; return out; }
|
||||
out.state = c.body?.current?.state || '알 수 없음';
|
||||
out.port = c.body?.current?.port || null;
|
||||
out.job = { file: j.body?.job?.file?.path || j.body?.job?.file?.name || null, completion: j.body?.progress?.completion ?? null, timeLeft: j.body?.progress?.printTimeLeft ?? null, state: j.body?.state || null };
|
||||
} catch (e: any) { out.error = String(e?.message || e); }
|
||||
return out;
|
||||
}
|
||||
|
||||
const safeName = (s: string) => String(s).replace(/[^A-Za-z0-9_.\-]/g, '_').slice(0, 60);
|
||||
|
||||
/** 파일을 OctoPrint 로컬 저장소의 pcb/ 폴더에 올린다(작업은 시작하지 않는다). */
|
||||
export async function uploadGcode(project: string, files: Record<string, string>): Promise<string[]> {
|
||||
const folder = 'pcb';
|
||||
const proj = safeName(project) || 'board';
|
||||
const done: string[] = [];
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
if (typeof content !== 'string' || content.length > 5_000_000) throw new Error(`${name}: 파일이 비었거나 너무 큽니다.`);
|
||||
// OctoPrint 는 .gcode/.gco/.g 만 받는다. 텍스트 안내(jumpers.txt)는 올리지 않는다.
|
||||
if (!/\.(nc|gcode|gco|g)$/i.test(name)) continue;
|
||||
const upName = `${proj}_${safeName(name).replace(/\.(nc|gco|g)$/i, '')}.gcode`.replace(/\.gcode\.gcode$/i, '.gcode');
|
||||
const form = new FormData();
|
||||
form.append('file', new Blob([content], { type: 'text/plain' }), upName);
|
||||
form.append('path', folder);
|
||||
const r = await octo('/api/files/local', { method: 'POST', body: form });
|
||||
if (r.status !== 201 && r.status !== 200) throw new Error(`${upName} 업로드 실패(${r.status}): ${typeof r.body === 'string' ? r.body.slice(0, 120) : r.body?.error || ''}`);
|
||||
done.push(`${folder}/${upName}`);
|
||||
}
|
||||
if (!done.length) throw new Error('올릴 G-code 파일이 없습니다.');
|
||||
return done;
|
||||
}
|
||||
|
||||
/** 업로드된 파일로 작업을 시작한다. 이미 작업 중이거나 연결이 안 되어 있으면 거부. */
|
||||
export async function startJob(filePath: string): Promise<void> {
|
||||
if (!/^pcb\/[A-Za-z0-9_.\-]+\.gcode$/.test(filePath)) throw new Error('pcb/ 폴더의 파일만 시작할 수 있습니다.');
|
||||
const st = await millStatus();
|
||||
if (!st.reachable) throw new Error(st.error || '옥토서버에 연결할 수 없습니다.');
|
||||
if (!/^operational$/i.test(String(st.state))) throw new Error(`머신 상태가 "${st.state}" 입니다. Operational(대기) 상태에서만 시작할 수 있습니다. OctoPrint 에서 연결을 확인하세요.`);
|
||||
const r = await octo(`/api/files/local/${filePath.split('/').map(encodeURIComponent).join('/')}`, { method: 'POST', json: { command: 'select', print: true } });
|
||||
if (r.status !== 204 && r.status !== 200) throw new Error(`시작 실패(${r.status}): ${r.body?.error || ''}`);
|
||||
}
|
||||
|
||||
export async function jobCommand(cmd: 'pause' | 'resume' | 'cancel'): Promise<void> {
|
||||
const body = cmd === 'cancel' ? { command: 'cancel' } : { command: 'pause', action: cmd };
|
||||
const r = await octo('/api/job', { method: 'POST', json: body });
|
||||
if (r.status !== 204 && r.status !== 200) throw new Error(`${cmd} 실패(${r.status}): ${r.body?.error || ''}`);
|
||||
}
|
||||
@@ -171,6 +171,8 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
<button class="btn pri" id="gbtn" style="width:100%" onclick="doGcode()">⚙ G-code 생성 · 미리보기</button>
|
||||
<div id="res"></div>
|
||||
<div class="dl" id="dl"></div>
|
||||
<h3>🏭 밀링 머신 (옥토서버)</h3>
|
||||
<div id="mill" class="note">확인 중…</div>
|
||||
</details>
|
||||
</aside>
|
||||
</div>
|
||||
@@ -479,7 +481,7 @@ async function doGcode(){
|
||||
const s=gres.stats;
|
||||
$('res').innerHTML=`구멍 ${s.holes}개(드릴 ${s.drillSizes.join(', ')||'-'}mm) · 격리 경로 ${s.isolationLengthMm}mm · 예상 약 ${s.estMinutes}분`+gres.warnings.map(w=>`<div class="warn">⚠ ${esc(w)}</div>`).join('');
|
||||
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 드릴(공구 교체 시 M0 일시정지) → 외곽. jumpers.txt 는 조립 시 윗면에 납땜할 점퍼선 목록입니다. 가공 전 Z 영점·고정을 확인하세요.</div>';
|
||||
draw();
|
||||
millPaths={};renderMill();draw();
|
||||
}catch(e){$('res').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
|
||||
finally{b.disabled=false;}
|
||||
}
|
||||
@@ -598,6 +600,62 @@ $('sc').addEventListener('mousemove',e=>{
|
||||
$('sc').addEventListener('mouseleave',()=>{simHover=null;drawChart();});
|
||||
new ResizeObserver(()=>drawChart()).observe($('simchart'));
|
||||
|
||||
|
||||
// ───────────── 밀링 머신(옥토서버 OctoPrint) ─────────────
|
||||
let millSt=null, millPaths={}, millProj='', millTimer=null;
|
||||
const millName=n=>n.replace(/\.(nc|gcode|gco|g)$/i,'');
|
||||
async function millRefresh(){
|
||||
try{ millSt=await api('/api/pcb/mill/status'); }catch(e){ millSt={error:e.message}; }
|
||||
renderMill();
|
||||
const busy=millSt&&millSt.job&&millSt.job.state&&/print|paus/i.test(millSt.job.state);
|
||||
clearTimeout(millTimer); if(busy) millTimer=setTimeout(millRefresh,3000);
|
||||
}
|
||||
function renderMill(){
|
||||
const el=$('mill'), st=millSt||{};
|
||||
if(!st.configured){
|
||||
el.innerHTML=`<div>밀링 OctoPrint 의 API 키가 필요합니다. <a href="https://mill.applecherry.net/" target="_blank" style="color:var(--brand2)">OctoPrint 설정 → API</a> 의 키를 아래에 붙여 넣으세요 (서버 금고에 암호화 저장, 관리자만).</div>
|
||||
<div style="display:flex;gap:4px;margin-top:6px"><input id="mkey" type="password" placeholder="API 키" autocomplete="off"><button class="btn" onclick="millSaveKey()">저장</button></div><div id="mkmsg"></div>`;
|
||||
return;
|
||||
}
|
||||
if(st.error&&!st.reachable){ el.innerHTML=`<span class="bad">${esc(st.error)}</span> <button class="btn" onclick="millRefresh()">↻</button> <button class="btn" onclick="millResetKey()">키 다시 입력</button>`; return; }
|
||||
const state=st.state||'?', job=st.job||{}, running=/print|paus/i.test(job.state||'');
|
||||
let h=`<div>상태: <b class="${/operational/i.test(state)?'ok':running?'warn':'bad'}">${esc(state)}</b>${st.port?` · ${esc(st.port)}`:''} <button class="btn" style="padding:1px 7px" onclick="millRefresh()">↻</button></div>`;
|
||||
if(running||job.file){ const pc=job.completion!=null?Math.round(job.completion):0; h+=`<div style="margin-top:4px">작업: ${esc(job.file||'-')} · ${esc(job.state||'')} ${running?pc+'%':''}</div>`;
|
||||
if(running) h+=`<div style="display:flex;gap:4px;margin-top:4px"><button class="btn" onclick="millJob('pause')">⏸ 일시정지</button><button class="btn" onclick="millJob('resume')">▶ 재개</button><button class="btn" onclick="millJob('cancel')" style="border-color:var(--red);color:var(--red)">■ 취소</button></div>`; }
|
||||
if(gres){
|
||||
const names=Object.keys(gres.files).filter(n=>/\.nc$/.test(n));
|
||||
const tool=n=>/copper/.test(n)?`공구: 가공 폭 ${P.mill.toolDia}mm 비트(V비트/엔드밀)`:/drill/.test(n)?`공구: 드릴 ${gres.stats.drillSizes.join(', ')||'-'}mm — 크기마다 M0에서 멈추니 공구 교체 후 ▶ 재개`:`공구: 엔드밀 Ø${P.mill.outlineDia}mm`;
|
||||
h+=names.map(n=>`<div class="net" style="margin-top:6px"><b>${esc(n)}</b>${millPaths[n]?' <span class="ok">· 업로드됨</span>':''}<div class="note">${esc(tool(n))}</div>
|
||||
<div style="display:flex;gap:4px;margin-top:4px"><button class="btn" onclick="millUpload('${esc(n)}')">⬆ 업로드</button><button class="btn pri" ${/operational/i.test(state)?'':'disabled'} onclick="millStart('${esc(n)}')">▶ 시작</button></div></div>`).join('');
|
||||
} else h+='<div class="note" style="margin-top:6px">G-code 를 생성하면 파일별로 올리고 시작할 수 있습니다.</div>';
|
||||
h+=`<div class="note">시작하면 스핀들이 돕니다. 시작 전에 Z 영점·기판 고정·공구를 확인하세요. <a href="https://mill.applecherry.net/" target="_blank" style="color:var(--brand2)">OctoPrint 열기 ↗</a> · <a href="#" onclick="millResetKey();return false" style="color:var(--muted)">키 변경</a></div><div id="mmsg"></div>`;
|
||||
el.innerHTML=h;
|
||||
}
|
||||
async function millSaveKey(){
|
||||
const k=$('mkey').value.trim(); if(!k) return;
|
||||
try{ await api('/api/pcb/mill/key',{key:k}); $('mkmsg').innerHTML='<span class="ok">저장됨</span>'; await millRefresh(); }
|
||||
catch(e){ $('mkmsg').innerHTML=`<span class="bad">${esc(e.message)}</span>`; }
|
||||
}
|
||||
function millResetKey(){ millSt={configured:false}; renderMill(); }
|
||||
function mmsg(h){ const e=$('mmsg'); if(e) e.innerHTML=h; }
|
||||
async function millUpload(name,quiet){
|
||||
if(!gres) return null;
|
||||
if(!millProj) millProj='board_'+new Date().toISOString().slice(0,16).replace(/[-:T]/g,'');
|
||||
try{ const d=await api('/api/pcb/mill/upload',{project:millProj,files:{[name]:gres.files[name]}}); millPaths[name]=d.uploaded[0]; renderMill(); if(!quiet) mmsg(`<span class="ok">✔ 업로드: ${esc(d.uploaded[0])}</span>`); return d.uploaded[0]; }
|
||||
catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); return null; }
|
||||
}
|
||||
async function millStart(name){
|
||||
const what=/copper/.test(name)?'격리 가공':/drill/.test(name)?'드릴':'외곽 컷';
|
||||
if(!confirm(`${what}(${name})을 시작합니다.\n\n□ Z 영점을 이 공구로 맞췄습니까?\n□ 기판이 단단히 고정됐습니까?\n□ 공구가 맞게 장착됐습니까?\n\n시작하면 스핀들이 돌고 머신이 움직입니다.`)) return;
|
||||
const path=millPaths[name]||await millUpload(name,true); if(!path) return;
|
||||
try{ await api('/api/pcb/mill/start',{file:path,confirm:true}); mmsg('<span class="ok">▶ 작업을 시작했습니다.</span>'); millRefresh(); }
|
||||
catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); }
|
||||
}
|
||||
async function millJob(cmd){
|
||||
if(cmd==='cancel'&&!confirm('진행 중인 작업을 취소할까요?')) return;
|
||||
try{ await api('/api/pcb/mill/job',{command:cmd}); await millRefresh(); }catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); }
|
||||
}
|
||||
|
||||
// ───────────── 시작 ─────────────
|
||||
(async function init(){
|
||||
try{FP=(await api('/api/pcb/footprints')).footprints;FPM=Object.fromEntries(FP.map(f=>[f.id,f]));}catch(e){$('lib').innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
|
||||
@@ -606,7 +664,7 @@ new ResizeObserver(()=>drawChart()).observe($('simchart'));
|
||||
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],fps:saved.fps||{},rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();registerFps();}
|
||||
else newProject(false);
|
||||
try{const k=await api('/api/pcb/kicad/status');$('kst').innerHTML=k.installed?`<span class="ok">● ${k.footprints.toLocaleString()} 풋프린트 · ${k.symbols.toLocaleString()} 심볼</span>`:'<span class="bad">미설치</span>';}catch(e){}
|
||||
renderLib();setMode('select');renderSim();resize();fitView();
|
||||
renderLib();setMode('select');renderSim();resize();fitView();millRefresh();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user