You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.4 KiB

7 months ago
// server.js
// 1. 'express' 모듈을 불러옵니다.
const express = require('express');
// 'path' 모듈은 파일 경로를 쉽게 다루게 해줍니다.
const path = require('path');
// [추가] 'child_process' 모듈에서 'spawn'을 불러옵니다.
const { spawn } = require('child_process');
// 2. Express 앱을 생성합니다.
const app = express();
const port = 3000;
// 3. 'public' 폴더의 파일들을 정적 파일로 제공하도록 설정합니다.
app.use(express.static(path.join(__dirname, 'public')));
// [추가] POST 요청의 JSON 본문(body)을 파싱하기 위한 미들웨어
app.use(express.json());
// 4. 루트 경로('/')로 접속하면 'index.html'(로그인 페이지)를 보냅니다.
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// 5. '/dashboard' 경로로 접속하면 'dashboard.html'(메인 페이지)를 보냅니다.
app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'dashboard.html'));
});
// [수정] 6. 모델 변경 API 엔드포인트
app.post('/set-model', (req, res) => {
const { model } = req.body; // app.js에서 보낸 { model: "..." }
if (!model) {
return res.status(400).json({ status: 'error', message: '모델 값이 없습니다.' });
}
console.log(`[서버] 모델 변경 명령 수신: ${model}`);
// --- 요청하신 파이썬 스크립트 실행 ---
const pythonCommand = 'python3';
const scriptPath = '/mnt/user_data/ctrl_cli.py';
// [수정] 인수를 " [선택값]" 형태의 단일 문자열로 만듭니다.
const combinedArg = `"ON ${model}"`;
// [수정] 수정된 인수를 배열에 담아 전달합니다.
const args = [scriptPath, combinedArg];
console.log(`[서버] 실행: ${pythonCommand} ${args.join(' ')}`); // 실행될 명령어 로그
const py = spawn(pythonCommand, args);
let stdoutData = '';
let stderrData = '';
// 파이썬 스크립트의 표준 출력
py.stdout.on('data', (data) => {
console.log(`Python stdout: ${data}`);
stdoutData += data.toString();
});
// 파이썬 스크립트의 표준 에러
py.stderr.on('data', (data) => {
console.error(`Python stderr: ${data}`);
stderrData += data.toString();
});
// 파이썬 프로세스 종료
py.on('close', (code) => {
console.log(`Python process exited with code ${code}`);
if (code === 0) {
// 성공 시 클라이언트에 응답
res.json({ status: 'success', message: `모델이 ${model}(으)로 변경됨`, output: stdoutData });
} else {
// 실패 시 클라이언트에 에러 응답
res.status(500).json({ status: 'error', message: '파이썬 스크립트 실행 실패', error: stderrData });
}
});
// 스폰 자체의 에러 (예: python3 명령어를 찾을 수 없음)
py.on('error', (err) => {
console.error('[서버] 파이썬 프로세스 시작 실패:', err);
res.status(500).json({ status: 'error', message: '프로세스 시작 실패', error: err.message });
});
// --- 스크립트 실행 끝 ---
});
// 7. (번호 수정) 설정한 3000번 포트에서 서버가 요청을 기다리도록 실행합니다.
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});