fix: nvr_snapshot이 NVR 채널 수를 4로 하드코딩 — 실제 조회로 변경 (우리 건 6채널)

/netsdk/Channel/IPCamInfo + Stat/IPC로 실제 연결된 채널만 나열(nvrEnabledChannelIds).
같은 라벨의 독립카메라(Mercusys)가 있으면 NVR쪽 항목 대신 직접 RTSP 쪽을 쓴다
(NVR ch5 = Mercusys인데 NVR쪽 연결은 Connect Failed).
독립카메라 라벨 변경 엔드포인트 POST /api/nvr/extra-cameras/:id/label 추가.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rfme1WVEPkpNwnf5oVNXXc
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-09-07 11:18:30 +09:00
1 parent 58a079fcb1
commit 2e2a689b32
2 files changed
+50 -10

No files matched your search

+36 -1
View File
@@ -82,6 +82,25 @@ export function getChannelLabels(): Record<string, string> {
return (cfg?.nvr?.channelLabels && typeof cfg.nvr.channelLabels === 'object') ? cfg.nvr.channelLabels : {};
}
// NVR에 붙어 있고 실제로 연결된 채널 ID 목록. 실패 시 [0,1,2,3] 폴백(이 기기 최소 구성).
// nvr_snapshot 도구가 "몇 채널이 있나"를 알아내는 데 쓴다 — 채널 수는 기기마다 다르다(우리 건 6개).
export async function nvrEnabledChannelIds(): Promise<number[]> {
try {
const [info, stat] = await Promise.all([
nvrFetch('/netsdk/Channel/IPCamInfo'),
nvrFetch('/netsdk/Stat/IPC').catch(() => [] as any[]),
]);
const okById = new Map<number, boolean>((Array.isArray(stat) ? stat : []).map((s: any) => [Number(s.ID), s.Status === 'Connect success']));
const ids = (Array.isArray(info) ? info : [])
.filter((c: any) => c.Enable === 'True' && okById.get(Number(c.ID)) !== false)
.map((c: any) => Number(c.ID))
.filter((n: number) => Number.isFinite(n));
return ids.length ? ids : [0, 1, 2, 3];
} catch {
return [0, 1, 2, 3];
}
}
// 채널(메인 NVR 0~3 또는 독립 카메라 1000+)의 RTSP URL을 조립한다. 라이브 스트림 라우트와
// nvr_snapshot 도구가 공유한다. stream: 0=메인(고화질) 1=서브(저화질).
export function buildRtspUrl(channelId: number, stream: 0 | 1 = 0): { url: string } | { error: string } {
@@ -157,7 +176,7 @@ async function onvifPtzControl(cam: ExtraCamera, command: string, speed: number)
});
}
async function nvrFetch(nvrPath: string, opts: { method?: string; body?: any } = {}): Promise<any> {
export async function nvrFetch(nvrPath: string, opts: { method?: string; body?: any } = {}): Promise<any> {
const { host, port, username, password } = getNvrConfig();
if (!host) throw new Error('NVR host not configured — set it via POST /api/nvr/config first');
const auth = Buffer.from(`${username}:${password}`).toString('base64');
@@ -348,6 +367,22 @@ export function registerNvrRoutes(app: Express): void {
res.json({ success: true, rotate180 });
});
// 독립 카메라 라벨 변경(NVR 채널 라벨과 대응 — nvr_snapshot이 이름으로 카메라를 찾는다).
app.post('/api/nvr/extra-cameras/:id/label', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const id = Number(req.params.id);
const label = String(req.body?.label ?? '').trim().slice(0, 60);
if (!label) return res.status(400).json({ error: 'label is required' });
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const list: any[] = Array.isArray(nvr.extraCameras) ? nvr.extraCameras : [];
const updated = list.map((c: any) => (Number(c.id) === id ? { ...c, label } : c));
cm.updateConfig({ nvr: { ...nvr, extraCameras: updated } } as any);
res.json({ success: true, label });
});
// ── 채널 이름/위치 라벨 ────────────────────────────────────────────────
// NVR 자체는 채널에 이름/위치 메타데이터가 없음(모델명·IP·MAC만 줌) — 카메라를
// "채널 3" 대신 "현관", "거실" 등으로 구분하고 싶다는 요청(2026-07-21)에 따라
+14 -9
View File
@@ -4,7 +4,7 @@ import path from 'path';
import { ToolResult } from '../types.js';
import { getWorkspacePath } from '../config/paths.js';
import { buildImageMarkdown } from './image.js';
import { buildRtspUrl, getExtraCameras, getChannelLabels } from '../gateway/routes/nvr.js';
import { buildRtspUrl, getExtraCameras, getChannelLabels, nvrEnabledChannelIds } from '../gateway/routes/nvr.js';
// 집 CCTV(NVR K8210-3WS 4채널 + 독립 IP카메라)의 현재 화면을 한 프레임 캡처해서
// 모델이 직접 보게 한다. RTSP → ffmpeg 단일 프레임 → workspace/nvr-snapshots/ 에 JPG 저장 →
@@ -12,23 +12,28 @@ import { buildRtspUrl, getExtraCameras, getChannelLabels } from '../gateway/rout
interface CamInfo { id: number; label: string; source: 'nvr' | 'standalone'; }
function listCameras(): CamInfo[] {
async function listCameras(): Promise<CamInfo[]> {
const labels = getChannelLabels();
const cams: CamInfo[] = [];
// 메인 NVR은 채널 개수를 조회하려면 /netsdk 왕복이 필요한데, 이 기기는 항상 4채널(0~3)
// 고정이라 그냥 4개로 둔다. 라벨 없는 채널은 "채널 N"으로 표기.
for (let i = 0; i < 4; i++) {
// 채널 수는 기기마다 다르다(우리 건 6개, 0~5) — NVR에 실제 물어본다. 실패 시 0~3 폴백.
const chIds = await nvrEnabledChannelIds();
for (const i of chIds) {
cams.push({ id: i, label: labels[String(i)] || `채널 ${i}`, source: 'nvr' });
}
// 독립 카메라(NVR 채널로도 등록돼 있지만 NVR 쪽 연결이 실패하는 Mercusys 등). 같은 라벨의
// NVR 채널이 이미 목록에 있으면 그건 빼고 이쪽(직접 RTSP)을 쓴다.
for (const c of getExtraCameras()) {
cams.push({ id: c.id, label: c.label || `카메라 ${c.id}`, source: 'standalone' });
const lbl = c.label || `카메라 ${c.id}`;
const twinIdx = cams.findIndex((x) => x.label === lbl);
if (twinIdx >= 0) cams.splice(twinIdx, 1);
cams.push({ id: c.id, label: lbl, source: 'standalone' });
}
return cams;
}
// "현관", "채널 2", "2", "머큐시스" 등 자유 입력을 채널 ID로 해석.
function resolveCameraId(input: unknown): { id: number; label: string } | { error: string } {
const cams = listCameras();
async function resolveCameraId(input: unknown): Promise<{ id: number; label: string } | { error: string }> {
const cams = await listCameras();
const list = () => cams.map((c) => `${c.label}(${c.id})`).join(', ');
if (input == null || String(input).trim() === '') {
return { error: `어느 카메라인지 지정하세요. 사용 가능: ${list()}` };
@@ -94,7 +99,7 @@ export const nvrSnapshotTool = {
additionalProperties: false,
},
execute: async (args: any): Promise<ToolResult> => {
const resolved = resolveCameraId(args?.camera);
const resolved = await resolveCameraId(args?.camera);
if ('error' in resolved) return { success: false, error: resolved.error };
const stream: 0 | 1 = String(args?.stream) === 'sub' ? 1 : 0;