Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
577edbec79 | ||
|
|
f3bed57e4d | ||
|
|
71ca95d7ce | ||
|
|
29cff2321a | ||
|
|
8a804e782a | ||
|
|
f7194ab2e4 | ||
|
|
c015861147 | ||
|
|
4d3f67277f |
No files matched your search
@@ -55,3 +55,5 @@ Thumbs.db
|
||||
|
||||
# Claude Code 本地状态(settings、定时任务锁等)
|
||||
.claude/
|
||||
host_key
|
||||
docs_dev/
|
||||
@@ -4,3 +4,7 @@ test-results/
|
||||
.env
|
||||
*.env
|
||||
!*.env.example
|
||||
|
||||
# 运行时持久化文件(自动生成)
|
||||
config/host_registry.json
|
||||
config/node_specs.json
|
||||
@@ -1,11 +1,13 @@
|
||||
"""远端主机管理 API。
|
||||
|
||||
提供主机的注册、查询、注销接口。注册信息保存在内存中(进程级),
|
||||
重启控制器后需要重新注册。
|
||||
提供主机的注册、查询、注销接口。注册信息持久化到 JSON 文件,
|
||||
控制器重启后自动恢复。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
@@ -16,10 +18,47 @@ log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/hosts", tags=["hosts"])
|
||||
|
||||
REGISTRY_PATH: Path = Path("/app/config/host_registry.json")
|
||||
|
||||
# 进程级内存存储:{host_ip: HostRegisterRequest}
|
||||
_registry: dict[str, HostRegisterRequest] = {}
|
||||
|
||||
|
||||
def _load_registry() -> None:
|
||||
"""从 JSON 文件加载主机注册表。"""
|
||||
if not REGISTRY_PATH.exists():
|
||||
return
|
||||
try:
|
||||
data = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
|
||||
for item in data:
|
||||
req = HostRegisterRequest(**item)
|
||||
_registry[req.ip] = req
|
||||
if _registry:
|
||||
log.info("已从 %s 恢复 %d 台主机", REGISTRY_PATH, len(_registry))
|
||||
except Exception as e:
|
||||
log.warning("加载主机注册表失败: %s", e)
|
||||
|
||||
|
||||
def _save_registry() -> None:
|
||||
"""将主机注册表持久化到 JSON 文件。"""
|
||||
data = [
|
||||
{
|
||||
"ip": h.ip,
|
||||
"ssh_user": h.ssh_user,
|
||||
"ssh_key": h.ssh_key,
|
||||
"capacity": h.capacity,
|
||||
"labels": h.labels,
|
||||
}
|
||||
for h in _registry.values()
|
||||
]
|
||||
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
REGISTRY_PATH.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
# 模块导入时自动恢复
|
||||
_load_registry()
|
||||
|
||||
|
||||
@router.post("/register")
|
||||
async def register_host(req: HostRegisterRequest) -> dict[str, Any]:
|
||||
"""注册远端主机。
|
||||
@@ -27,6 +66,7 @@ async def register_host(req: HostRegisterRequest) -> dict[str, Any]:
|
||||
同一 IP 重复注册会覆盖旧记录。
|
||||
"""
|
||||
_registry[req.ip] = req
|
||||
_save_registry()
|
||||
log.info("注册远端主机 %s (user=%s capacity=%d)", req.ip, req.ssh_user, req.capacity)
|
||||
return {
|
||||
"ok": True,
|
||||
@@ -50,12 +90,33 @@ async def list_hosts() -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
@router.put("/{host_ip}")
|
||||
async def update_host(host_ip: str, req: HostRegisterRequest) -> dict[str, Any]:
|
||||
"""更新远端主机的 SSH 凭据、容量等信息。
|
||||
|
||||
调用时必须与现有 host_ip 一致(或使用 URL 中的 IP)。
|
||||
"""
|
||||
if host_ip not in _registry:
|
||||
raise HTTPException(404, f"主机 {host_ip} 未注册")
|
||||
updated = req.model_copy(update={"ip": host_ip})
|
||||
_registry[host_ip] = updated
|
||||
_save_registry()
|
||||
log.info("更新远端主机 %s (user=%s capacity=%d)", host_ip, updated.ssh_user, updated.capacity)
|
||||
return {
|
||||
"ok": True,
|
||||
"ip": host_ip,
|
||||
"ssh_user": updated.ssh_user,
|
||||
"capacity": updated.capacity,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{host_ip}")
|
||||
async def deregister_host(host_ip: str) -> dict[str, Any]:
|
||||
"""注销远端主机。"""
|
||||
if host_ip not in _registry:
|
||||
raise HTTPException(404, f"主机 {host_ip} 未注册")
|
||||
del _registry[host_ip]
|
||||
_save_registry()
|
||||
log.info("注销远端主机 %s", host_ip)
|
||||
return {"ok": True, "ip": host_ip}
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""节点操作路由:GET/POST /api/nodes、/api/flows、/api/logs。"""
|
||||
"""节点操作路由:GET/POST /api/nodes、/api/flows、/api/logs 以及节点配置持久化。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
@@ -12,6 +14,24 @@ from pydantic import BaseModel, field_validator
|
||||
|
||||
from controller.api.state import get_session
|
||||
|
||||
NODE_SPECS_PATH: Path = Path("/app/config/node_specs.json")
|
||||
|
||||
|
||||
def _load_node_specs() -> list[dict[str, Any]]:
|
||||
"""从 JSON 文件加载节点配置。"""
|
||||
if not NODE_SPECS_PATH.exists():
|
||||
return []
|
||||
try:
|
||||
return json.loads(NODE_SPECS_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _save_node_specs(specs: list[dict[str, Any]]) -> None:
|
||||
"""将节点配置持久化到 JSON 文件。"""
|
||||
NODE_SPECS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
NODE_SPECS_PATH.write_text(json.dumps(specs, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["nodes"])
|
||||
@@ -63,6 +83,24 @@ def _validate_cmd(cmd: str | list[str]) -> None:
|
||||
raise HTTPException(400, f"命令 '{name}' 不在白名单内")
|
||||
|
||||
|
||||
class NodeSpecsBody(BaseModel):
|
||||
"""节点配置列表的请求体。"""
|
||||
specs: list[dict[str, Any]]
|
||||
|
||||
|
||||
@router.get("/api/nodes/specs")
|
||||
async def get_node_specs() -> list[dict[str, Any]]:
|
||||
"""获取保存的节点配置列表。"""
|
||||
return _load_node_specs()
|
||||
|
||||
|
||||
@router.put("/api/nodes/specs")
|
||||
async def save_node_specs(body: NodeSpecsBody) -> dict[str, Any]:
|
||||
"""保存节点配置列表。"""
|
||||
_save_node_specs(body.specs)
|
||||
return {"ok": True, "count": len(body.specs)}
|
||||
|
||||
|
||||
class ExecBody(BaseModel):
|
||||
"""节点内执行命令的请求体。"""
|
||||
cmd: str | list[str]
|
||||
|
||||
@@ -3,11 +3,15 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from controller.api.state import Session, get_session
|
||||
from controller.orchestrator import RunRequest, PRESETS
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/sim", tags=["sim"])
|
||||
|
||||
|
||||
@@ -28,6 +32,7 @@ async def start_sim(req: RunRequest | None = None) -> dict[str, Any]:
|
||||
except KeyError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.exception("仿真启动失败")
|
||||
raise HTTPException(500, f"启动失败: {e!r}") from e
|
||||
return {"ok": True, "running": sess.running, "nNodes": sess.config.n_nodes}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ from controller.orchestrator.netns import (
|
||||
create_vxlan_on_controller,
|
||||
delete_link,
|
||||
list_stale_links,
|
||||
mesh_mac,
|
||||
node_bridge_name,
|
||||
teardown,
|
||||
)
|
||||
@@ -335,10 +336,42 @@ class Session:
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("恢复快照失败: %s", e)
|
||||
|
||||
# 5. 启动容器状态缓存刷新(本地节点)
|
||||
# 5. 注入静态 ARP 条目(避免 mesh+VXLAN 路径下广播 ARP 不可达)
|
||||
for spec in specs:
|
||||
for peer in specs:
|
||||
if spec.id >= peer.id:
|
||||
continue
|
||||
peer_mac = mesh_mac(peer.id)
|
||||
my_mac = mesh_mac(spec.id)
|
||||
if spec.host == "local":
|
||||
try:
|
||||
docker_mgr.exec_in(spec.id, f"arp -s {peer.ip} {peer_mac}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 node %d -> %s: %s", spec.id, peer.ip, e)
|
||||
elif spec.host_type == "host-manet":
|
||||
mgr = host_mgrs.get(spec.host)
|
||||
if mgr:
|
||||
try:
|
||||
mgr.exec_on_host(f"sudo arp -s {peer.ip} {peer_mac} dev vxlan-{spec.id}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 host-node %d -> %s: %s", spec.id, peer.ip, e)
|
||||
if peer.host == "local":
|
||||
try:
|
||||
docker_mgr.exec_in(peer.id, f"arp -s {spec.ip} {my_mac}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 node %d -> %s: %s", peer.id, spec.ip, e)
|
||||
elif peer.host_type == "host-manet":
|
||||
mgr = host_mgrs.get(peer.host)
|
||||
if mgr:
|
||||
try:
|
||||
mgr.exec_on_host(f"sudo arp -s {spec.ip} {my_mac} dev vxlan-{peer.id}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 host-node %d -> %s: %s", peer.id, spec.ip, e)
|
||||
|
||||
# 6. 启动容器状态缓存刷新(本地节点)
|
||||
docker_mgr.start_status_refresh(interval=1.0)
|
||||
|
||||
# 6. 启动遥测泵 (5 Hz)
|
||||
# 7. 启动遥测泵 (5 Hz)
|
||||
# 统一的状态检查函数,覆盖本地、host、远端节点
|
||||
specs_by_id = {s.id: s for s in specs}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ creates a matching VXLAN + bridge + TAP for each host node.
|
||||
Data path:
|
||||
|
||||
Host App → vxlan-{id} ── UDP/4789 ──► Controller vxlan-{id}
|
||||
│
|
||||
|
|
||||
mesh-br-{id}
|
||||
├── mesh-tap-{id} → ns-3 PHY/MAC
|
||||
|
||||
@@ -18,6 +18,7 @@ to SSH-start the container and create the controller-side bridge + TAP.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
@@ -37,11 +38,11 @@ log = logging.getLogger(__name__)
|
||||
HOST_CONTAINER_PREFIX = "manet-host-node-"
|
||||
|
||||
|
||||
def _load_pkey(key_path: str) -> Optional["paramiko.PKey"]:
|
||||
"""Try loading a private key file, auto-detecting the type."""
|
||||
def _load_pkey(key_data: str) -> Optional["paramiko.PKey"]:
|
||||
"""Try loading a private key from its PEM/OpenSSH content string."""
|
||||
for cls in (RSAKey, Ed25519Key, ECDSAKey):
|
||||
try:
|
||||
return cls.from_private_key_file(key_path)
|
||||
return cls.from_private_key(io.StringIO(key_data))
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
@@ -110,7 +111,7 @@ class HostNodeMgr:
|
||||
if pkey is not None:
|
||||
connect_kwargs["pkey"] = pkey
|
||||
else:
|
||||
connect_kwargs["key_filename"] = self.ssh_key
|
||||
raise ValueError(f"无法解析 SSH 私钥 (host={self.host_ip})")
|
||||
elif self.ssh_password:
|
||||
connect_kwargs["password"] = self.ssh_password
|
||||
client.connect(**connect_kwargs)
|
||||
@@ -283,6 +284,10 @@ class HostNodeMgr:
|
||||
self.stop_one(nid)
|
||||
|
||||
# ------------------------------------------------------------------ exec / logs / status
|
||||
def exec_on_host(self, cmd: str, timeout: int = 30) -> tuple[int, str]:
|
||||
"""Execute a command directly on the remote host (not inside a container)."""
|
||||
return self._exec(cmd, timeout)
|
||||
|
||||
def exec_in(self, node_id: int, cmd: str | list[str]) -> tuple[int, str]:
|
||||
"""Execute a command inside the host-manet-node container."""
|
||||
hn = self._nodes.get(node_id)
|
||||
|
||||
@@ -8,10 +8,10 @@ import { ConfigPanel } from '@/sections/ConfigPanel';
|
||||
import { TopologyView } from '@/sections/TopologyView';
|
||||
import { LogView } from '@/sections/LogView';
|
||||
import { DynamicControl } from '@/sections/DynamicControl';
|
||||
import { ProtoTest } from '@/sections/ProtoTest';
|
||||
import { NodeManager } from '@/sections/NodeManager';
|
||||
import type { NodeSpec } from '@/types/config';
|
||||
import {
|
||||
LayoutDashboard, Settings, Network, ScrollText, Zap, Radio,
|
||||
LayoutDashboard, Settings, Network, ScrollText, Zap, Server,
|
||||
Play, Square, RotateCw, Wifi, Route,
|
||||
} from 'lucide-react';
|
||||
import './App.css';
|
||||
@@ -24,7 +24,7 @@ const NAV_ITEMS = [
|
||||
{ key: 'dashboard', label: '仪表板', icon: LayoutDashboard },
|
||||
{ key: 'config', label: '配置', icon: Settings },
|
||||
{ key: 'dynamic', label: '动态控制', icon: Zap },
|
||||
{ key: 'proto', label: '协议测试', icon: Radio },
|
||||
{ key: 'nodes', label: '节点管理', icon: Server },
|
||||
{ key: 'logs', label: '日志', icon: ScrollText },
|
||||
] as const;
|
||||
|
||||
@@ -327,10 +327,8 @@ function App() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activePage === 'proto' && (
|
||||
<div className="h-full overflow-hidden animate-fade-in">
|
||||
<ProtoTest />
|
||||
</div>
|
||||
{activePage === 'nodes' && (
|
||||
<NodeManager onNodeSpecsChange={setNodeSpecs} />
|
||||
)}
|
||||
|
||||
{activePage === 'logs' && (
|
||||
|
||||
@@ -170,47 +170,53 @@ export function useSimConfig(sim?: SimApi) {
|
||||
setActivePreset('custom');
|
||||
}, []);
|
||||
|
||||
// ---- auto-save to backend via WebSocket (debounce 500ms) ----
|
||||
// ---- auto-save to backend via REST PUT /api/config (debounce 500ms) ----
|
||||
// 优先使用 REST 保存配置,可靠且不需要 WebSocket 连接。
|
||||
const saveConfig = useCallback(async (cfg: SimConfig) => {
|
||||
if (!sim) {
|
||||
// 无 WebSocket 时回退到 REST PUT
|
||||
setSaveStatus('saving');
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(cfg),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} catch {
|
||||
setSaveStatus('error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus('saving');
|
||||
try {
|
||||
const params: Record<string, unknown> = {};
|
||||
(Object.keys(cfg) as Array<keyof SimConfig>).forEach(key => {
|
||||
params[key] = cfg[key];
|
||||
const res = await fetch(`${API_BASE}/api/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(cfg),
|
||||
});
|
||||
const result = await sim.batchSetParams(params);
|
||||
// 忽略预期内的失败(如运行时不可修改的参数),只把真正异常视为错误
|
||||
const realFailures = (result.results || []).filter(
|
||||
(r: any) => !r.ok && !(r.reason || '').includes('requires simulator restart')
|
||||
);
|
||||
if (realFailures.length === 0) {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} else {
|
||||
console.warn('save failed for keys:', realFailures.map((r: any) => r.key));
|
||||
setSaveStatus('error');
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
if (data.ok === false) {
|
||||
const reasons = (data.results || [])
|
||||
.filter((r: { ok?: boolean }) => r.ok === false)
|
||||
.map((r: { key?: string; reason?: string }) => r.key || r.reason || 'unknown')
|
||||
.join(', ');
|
||||
if (reasons) console.warn('save partial failures:', reasons);
|
||||
}
|
||||
} catch {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} catch (e) {
|
||||
console.warn('saveConfig REST failed:', e);
|
||||
|
||||
// 兜底:WebSocket 路径(仿真运行中需要实时下发的参数)
|
||||
if (sim) {
|
||||
try {
|
||||
const params: Record<string, unknown> = {};
|
||||
(Object.keys(cfg) as Array<keyof SimConfig>).forEach(key => {
|
||||
params[key] = cfg[key];
|
||||
});
|
||||
const result = await sim.batchSetParams(params);
|
||||
const realFailures = (result.results || []).filter(
|
||||
(r: { ok: boolean; reason?: string }) => !r.ok && !(r.reason || '').includes('requires simulator restart')
|
||||
);
|
||||
if (realFailures.length === 0) {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// WS 也失败,继续报 error
|
||||
}
|
||||
}
|
||||
|
||||
setSaveStatus('error');
|
||||
}
|
||||
}, [sim]);
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NodeSpec } from '@/types/config';
|
||||
import {
|
||||
Plus, Trash2, Server, Globe, Wifi,
|
||||
Loader2, RefreshCw, Network, Pencil, Save,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface RemoteHost {
|
||||
ip: string;
|
||||
ssh_user: string;
|
||||
capacity: number;
|
||||
}
|
||||
|
||||
interface NodeManagerProps {
|
||||
onNodeSpecsChange?: (specs: NodeSpec[] | undefined) => void;
|
||||
}
|
||||
|
||||
export function NodeManager({ onNodeSpecsChange }: NodeManagerProps) {
|
||||
// ---- remote host management ----
|
||||
const [remoteHosts, setRemoteHosts] = useState<RemoteHost[]>([]);
|
||||
const [loadingHosts, setLoadingHosts] = useState(false);
|
||||
|
||||
const [newHostIp, setNewHostIp] = useState('');
|
||||
const [newHostUser, setNewHostUser] = useState('root');
|
||||
const [newHostKey, setNewHostKey] = useState('');
|
||||
const [newHostCapacity, setNewHostCapacity] = useState(4);
|
||||
const [registering, setRegistering] = useState(false);
|
||||
const [editingHost, setEditingHost] = useState<string | null>(null);
|
||||
const [editHostUser, setEditHostUser] = useState('');
|
||||
const [editHostKey, setEditHostKey] = useState('');
|
||||
const [editHostCapacity, setEditHostCapacity] = useState(4);
|
||||
|
||||
// ---- node configuration ----
|
||||
const [nodeSpecs, setNodeSpecs] = useState<NodeSpec[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Load node specs from backend on mount
|
||||
const fetchNodeSpecs = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/nodes/specs');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
setNodeSpecs(data);
|
||||
} else {
|
||||
// Default fallback: 2 local nodes
|
||||
setNodeSpecs([
|
||||
{ id: 0, ip: '192.168.100.10', role: 'server', host: 'local' },
|
||||
{ id: 1, ip: '192.168.100.11', role: 'client', host: 'local' },
|
||||
]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Save node specs to backend with debounce
|
||||
const saveNodeSpecs = useCallback(async (specs: NodeSpec[]) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await fetch('/api/nodes/specs', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ specs }),
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Debounced save: wait 500ms after last change
|
||||
const debouncedSave = useCallback((specs: NodeSpec[]) => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => saveNodeSpecs(specs), 500);
|
||||
}, [saveNodeSpecs]);
|
||||
|
||||
const fetchHosts = useCallback(async () => {
|
||||
setLoadingHosts(true);
|
||||
try {
|
||||
const res = await fetch('/api/hosts');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setRemoteHosts(Array.isArray(data) ? data : []);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setLoadingHosts(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { fetchHosts(); fetchNodeSpecs(); }, [fetchHosts, fetchNodeSpecs]);
|
||||
|
||||
const registerHost = async () => {
|
||||
if (!newHostIp.trim()) return;
|
||||
setRegistering(true);
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
ip: newHostIp.trim(),
|
||||
ssh_user: newHostUser,
|
||||
capacity: newHostCapacity,
|
||||
};
|
||||
if (newHostKey.trim()) body.ssh_key = newHostKey.trim();
|
||||
const res = await fetch('/api/hosts/register', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.ok) {
|
||||
await fetchHosts();
|
||||
setNewHostIp('');
|
||||
setNewHostUser('root');
|
||||
setNewHostKey('');
|
||||
setNewHostCapacity(4);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setRegistering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const unregisterHost = async (ip: string) => {
|
||||
try {
|
||||
await fetch(`/api/hosts/${ip}`, { method: 'DELETE' });
|
||||
await fetchHosts();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const startEditHost = (host: RemoteHost) => {
|
||||
setEditingHost(host.ip);
|
||||
setEditHostUser(host.ssh_user);
|
||||
setEditHostKey('');
|
||||
setEditHostCapacity(host.capacity);
|
||||
};
|
||||
|
||||
const saveEditHost = async () => {
|
||||
if (!editingHost) return;
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
ip: editingHost,
|
||||
ssh_user: editHostUser,
|
||||
capacity: editHostCapacity,
|
||||
};
|
||||
if (editHostKey.trim()) body.ssh_key = editHostKey.trim();
|
||||
const res = await fetch(`/api/hosts/${editingHost}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.ok) {
|
||||
await fetchHosts();
|
||||
setEditingHost(null);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const cancelEditHost = () => {
|
||||
setEditingHost(null);
|
||||
};
|
||||
|
||||
// ---- node spec management ----
|
||||
const addNode = () => {
|
||||
const maxId = nodeSpecs.reduce((max, n) => Math.max(max, n.id), -1);
|
||||
const newId = maxId + 1;
|
||||
const newIp = `192.168.100.${10 + newId}`;
|
||||
const updated = [...nodeSpecs, {
|
||||
id: newId,
|
||||
ip: newIp,
|
||||
role: 'client' as const,
|
||||
host: 'local' as const,
|
||||
}];
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
const removeNode = (id: number) => {
|
||||
const updated = nodeSpecs.filter(n => n.id !== id);
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
const updateNode = (id: number, field: keyof NodeSpec, value: string) => {
|
||||
const updated = nodeSpecs.map(n =>
|
||||
n.id === id ? { ...n, [field]: value } : n
|
||||
);
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
// generate updated NodeSpec list whenever specs change
|
||||
const hasRemote = nodeSpecs.some(n => n.host !== 'local');
|
||||
useEffect(() => {
|
||||
if (onNodeSpecsChange) {
|
||||
onNodeSpecsChange(hasRemote ? nodeSpecs : undefined);
|
||||
}
|
||||
}, [nodeSpecs, hasRemote, onNodeSpecsChange]);
|
||||
|
||||
// Clean up debounce timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto p-4 space-y-5 max-w-6xl mx-auto animate-fade-in">
|
||||
{/* ---- Remote Hosts ---- */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3 flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Globe className="h-4 w-4 text-primary" />
|
||||
远端主机管理
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{remoteHosts.length} 台
|
||||
</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={fetchHosts} disabled={loadingHosts} className="h-7 w-7 p-0">
|
||||
<RefreshCw className={cn('h-3.5 w-3.5', loadingHosts && 'animate-spin')} />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{/* Add host form */}
|
||||
<div className="flex items-end gap-2 flex-wrap">
|
||||
<div className="flex-1 min-w-[140px]">
|
||||
<Label className="text-xs text-muted-foreground">IP 地址</Label>
|
||||
<Input
|
||||
value={newHostIp}
|
||||
onChange={e => setNewHostIp(e.target.value)}
|
||||
placeholder="192.168.1.100"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[100px]">
|
||||
<Label className="text-xs text-muted-foreground">SSH 用户</Label>
|
||||
<Input
|
||||
value={newHostUser}
|
||||
onChange={e => setNewHostUser(e.target.value)}
|
||||
placeholder="root"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[160px]">
|
||||
<Label className="text-xs text-muted-foreground">SSH 密钥路径</Label>
|
||||
<Input
|
||||
value={newHostKey}
|
||||
onChange={e => setNewHostKey(e.target.value)}
|
||||
placeholder="/path/to/key"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[80px]">
|
||||
<Label className="text-xs text-muted-foreground">容量</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={64}
|
||||
value={newHostCapacity}
|
||||
onChange={e => setNewHostCapacity(Number(e.target.value))}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={registerHost} disabled={registering || !newHostIp.trim()} className="h-9 gap-1.5">
|
||||
{registering ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
|
||||
注册
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Host list */}
|
||||
{remoteHosts.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-6 border rounded-lg bg-muted/30">
|
||||
<Server className="h-6 w-6 mx-auto mb-2 opacity-30" />
|
||||
暂无已注册的远端主机
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{remoteHosts.map(host => (
|
||||
editingHost === host.ip ? (
|
||||
<div key={host.ip} className="flex items-end gap-2 px-3 py-2 rounded-lg border bg-accent/30 text-sm">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-xs text-muted-foreground">SSH 用户</Label>
|
||||
<Input value={editHostUser} onChange={e => setEditHostUser(e.target.value)} className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Label className="text-xs text-muted-foreground">SSH 密钥路径</Label>
|
||||
<Input value={editHostKey} onChange={e => setEditHostKey(e.target.value)} placeholder="留空不变" className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<div className="w-[70px]">
|
||||
<Label className="text-xs text-muted-foreground">容量</Label>
|
||||
<Input type="number" min={1} max={64} value={editHostCapacity} onChange={e => setEditHostCapacity(Number(e.target.value))} className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<Button size="sm" onClick={saveEditHost} className="h-8 gap-1">保存</Button>
|
||||
<Button size="sm" variant="ghost" onClick={cancelEditHost} className="h-8">取消</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
key={host.ip}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg border bg-card text-sm hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
<Globe className="h-4 w-4 text-primary shrink-0" />
|
||||
<span className="font-mono font-medium">{host.ip}</span>
|
||||
<Badge variant="secondary" className="text-[10px]">{host.ssh_user}</Badge>
|
||||
<Badge variant="outline" className="text-[10px] ml-auto">容量 {host.capacity}</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={() => startEditHost(host)} className="h-7 w-7 p-0">
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => unregisterHost(host.ip)} className="h-7 w-7 p-0 text-destructive hover:text-destructive">
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ---- Node Configuration ---- */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3 flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Network className="h-4 w-4 text-primary" />
|
||||
节点配置
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
{saving ? (
|
||||
<Badge variant="outline" className="text-xs text-muted-foreground gap-1">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
保存中
|
||||
</Badge>
|
||||
) : nodeSpecs.length > 0 && (
|
||||
<Badge variant="outline" className="text-xs text-green-600 gap-1">
|
||||
<Save className="h-3 w-3" />
|
||||
已保存
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{nodeSpecs.length} 节点
|
||||
</Badge>
|
||||
<Button size="sm" onClick={addNode} className="h-8 gap-1.5">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
添加节点
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{/* Header */}
|
||||
<div className="grid grid-cols-12 gap-2 px-3 py-1.5 text-xs font-medium text-muted-foreground border-b">
|
||||
<div className="col-span-1">ID</div>
|
||||
<div className="col-span-3">IP 地址</div>
|
||||
<div className="col-span-2">角色</div>
|
||||
<div className="col-span-4">主机</div>
|
||||
<div className="col-span-2" />
|
||||
</div>
|
||||
|
||||
{nodeSpecs.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-8 border rounded-lg bg-muted/30">
|
||||
<Wifi className="h-6 w-6 mx-auto mb-2 opacity-30" />
|
||||
暂无节点,点击"添加节点"创建
|
||||
</div>
|
||||
) : (
|
||||
nodeSpecs.map((spec) => (
|
||||
<div
|
||||
key={spec.id}
|
||||
className="grid grid-cols-12 gap-2 items-center px-3 py-2 rounded-lg border bg-card hover:bg-accent/30 transition-colors"
|
||||
>
|
||||
<div className="col-span-1 font-mono text-sm font-medium">{spec.id}</div>
|
||||
<div className="col-span-3">
|
||||
<Input
|
||||
value={spec.ip}
|
||||
onChange={e => updateNode(spec.id, 'ip', e.target.value)}
|
||||
className="h-8 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<select
|
||||
value={spec.role}
|
||||
onChange={e => updateNode(spec.id, 'role', e.target.value)}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value="server">Server</option>
|
||||
<option value="client">Client</option>
|
||||
<option value="gateway">Gateway</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-span-4">
|
||||
<select
|
||||
value={spec.host}
|
||||
onChange={e => updateNode(spec.id, 'host', e.target.value)}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value="local">本机 (Local)</option>
|
||||
{remoteHosts.map(h => (
|
||||
<option key={h.ip} value={h.ip}>{h.ip}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-span-2 flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => removeNode(spec.id)}
|
||||
disabled={nodeSpecs.length <= 1}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
{hasRemote && (
|
||||
<div className="flex items-center gap-2 mt-2 px-3 py-2 rounded-lg bg-amber-50/80 border border-amber-200/60 text-xs text-amber-800">
|
||||
<Wifi className="h-3.5 w-3.5 shrink-0" />
|
||||
检测到远端节点,启动仿真时将自动创建对应 VXLAN 隧道
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Wifi, Send, Trash2, Radio, Settings, RefreshCw,
|
||||
ChevronDown, ChevronRight, Clock, Plug, Unplug,
|
||||
Cpu, Network, MessageSquare,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface Message {
|
||||
id: number;
|
||||
direction: 'sent' | 'received';
|
||||
timestamp: string;
|
||||
payload: string;
|
||||
pretty?: string;
|
||||
}
|
||||
|
||||
const NET_MODE_OPTIONS = [
|
||||
{ value: 1, label: '自组网' },
|
||||
{ value: 2, label: 'LTE' },
|
||||
{ value: 3, label: '天通' },
|
||||
{ value: 4, label: '173RAP' },
|
||||
{ value: 5, label: '173PRN' },
|
||||
{ value: 6, label: '北斗' },
|
||||
{ value: 7, label: 'UV' },
|
||||
{ value: 12, label: '173FCS' },
|
||||
];
|
||||
|
||||
const POWER_OPTIONS = [
|
||||
{ value: 0, label: '值守' },
|
||||
{ value: 1, label: '低' },
|
||||
{ value: 2, label: '中' },
|
||||
{ value: 3, label: '高' },
|
||||
];
|
||||
|
||||
const RATE_OPTIONS = [
|
||||
{ value: 1, label: '9.6kb' },
|
||||
{ value: 2, label: '19.2kb' },
|
||||
{ value: 3, label: '38.4kb' },
|
||||
{ value: 4, label: '62.5kb' },
|
||||
];
|
||||
|
||||
function buildFrame(data: Record<string, unknown>) {
|
||||
return JSON.stringify({
|
||||
data,
|
||||
ident: '',
|
||||
mnemonic: 0,
|
||||
resWord: '',
|
||||
type: 0,
|
||||
version: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export function ProtoTest() {
|
||||
const [wsUrl, setWsUrl] = useState('ws://100.100.100.3:8000/ws/radio');
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [customPayload, setCustomPayload] = useState('');
|
||||
const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({
|
||||
query: true,
|
||||
set: true,
|
||||
report: false,
|
||||
reportCfg: false,
|
||||
});
|
||||
|
||||
const [report5002Enabled, setReport5002Enabled] = useState(1);
|
||||
const [report5002Period, setReport5002Period] = useState(2000);
|
||||
const [report5006Enabled, setReport5006Enabled] = useState(1);
|
||||
const [report5006Period, setReport5006Period] = useState(10000);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const msgIdRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [netMode, setNetMode] = useState(1);
|
||||
const [ctrl, setCtrl] = useState(1);
|
||||
const [power, setPower] = useState(1);
|
||||
const [freqNum, setFreqNum] = useState(1);
|
||||
const [frequency, setFrequency] = useState(225);
|
||||
const [rate, setRate] = useState(2);
|
||||
const [extend, setExtend] = useState('KZ');
|
||||
|
||||
const [ns3Nodes, setNs3Nodes] = useState<Array<{ id: number; ip: string; status: string }>>([]);
|
||||
const [ns3Loading, setNs3Loading] = useState(false);
|
||||
|
||||
const fetchNs3Nodes = useCallback(async () => {
|
||||
setNs3Loading(true);
|
||||
try {
|
||||
const res = await fetch('/api/nodes');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setNs3Nodes(data);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setNs3Loading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchNs3Nodes();
|
||||
const timer = setInterval(fetchNs3Nodes, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}, [fetchNs3Nodes]);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
const addMessage = useCallback((direction: 'sent' | 'received', payload: string) => {
|
||||
let pretty = '';
|
||||
try {
|
||||
pretty = JSON.stringify(JSON.parse(payload), null, 2);
|
||||
} catch {
|
||||
pretty = payload;
|
||||
}
|
||||
setMessages(prev => [...prev, {
|
||||
id: ++msgIdRef.current,
|
||||
direction,
|
||||
timestamp: new Date().toLocaleTimeString(),
|
||||
payload,
|
||||
pretty,
|
||||
}]);
|
||||
}, []);
|
||||
|
||||
const connect = useCallback(() => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) return;
|
||||
try {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
ws.onopen = () => {
|
||||
setConnected(true);
|
||||
addMessage('received', `// 已连接到 ${wsUrl}`);
|
||||
};
|
||||
ws.onmessage = (ev) => {
|
||||
addMessage('received', ev.data);
|
||||
};
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
addMessage('received', `// 连接已关闭 ${wsUrl}`);
|
||||
wsRef.current = null;
|
||||
};
|
||||
ws.onerror = (e) => {
|
||||
setConnected(false);
|
||||
addMessage('received', `// 连接错误: ${(e as ErrorEvent).message || 'unknown'}`);
|
||||
wsRef.current = null;
|
||||
};
|
||||
wsRef.current = ws;
|
||||
} catch (e) {
|
||||
addMessage('received', `// 连接失败: ${(e as Error).message}`);
|
||||
}
|
||||
}, [wsUrl, addMessage]);
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
wsRef.current?.close();
|
||||
wsRef.current = null;
|
||||
setConnected(false);
|
||||
}, []);
|
||||
|
||||
const send = useCallback((payload: string) => {
|
||||
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
||||
addMessage('received', '// 错误: WebSocket 未连接');
|
||||
return;
|
||||
}
|
||||
wsRef.current.send(payload);
|
||||
addMessage('sent', payload);
|
||||
}, [addMessage]);
|
||||
|
||||
const sendCmd = useCallback((cmdCode: number, extra: Record<string, unknown> = {}) => {
|
||||
const payload = buildFrame({ cmdCode, extend, ...extra });
|
||||
send(payload);
|
||||
}, [extend, send]);
|
||||
|
||||
const clearMessages = useCallback(() => setMessages([]), []);
|
||||
|
||||
const toggleGroup = (key: string) => {
|
||||
setExpandedGroups(prev => ({ ...prev, [key]: !prev[key] }));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col overflow-hidden p-4 gap-3">
|
||||
{/* 顶部连接栏 */}
|
||||
<div className="flex items-center gap-3 shrink-0 bg-card rounded-xl border border-slate-200/60 p-3 shadow-card">
|
||||
<div className={cn(
|
||||
'h-3 w-3 rounded-full shrink-0 ring-2 ring-offset-1 ring-offset-background transition-all',
|
||||
connected ? 'bg-success ring-success/30 status-glow-green' : 'bg-destructive ring-destructive/30'
|
||||
)} />
|
||||
<span className="text-sm font-semibold shrink-0">
|
||||
{connected ? '已连接' : '未连接'}
|
||||
</span>
|
||||
<Input
|
||||
value={wsUrl}
|
||||
onChange={e => setWsUrl(e.target.value)}
|
||||
placeholder="ws://host:port"
|
||||
className="flex-1 h-9 text-sm"
|
||||
disabled={connected}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={connected ? disconnect : connect}
|
||||
variant={connected ? 'destructive' : 'default'}
|
||||
className="h-9 gap-1.5"
|
||||
>
|
||||
{connected ? <Unplug className="h-3.5 w-3.5" /> : <Plug className="h-3.5 w-3.5" />}
|
||||
{connected ? '断开' : '连接'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 主体 */}
|
||||
<div className="flex-1 min-h-0 flex gap-3">
|
||||
{/* 左侧面板:命令 */}
|
||||
<div className="w-[400px] shrink-0 flex flex-col gap-2 overflow-auto pr-1">
|
||||
{/* 公共参数 */}
|
||||
<div className="border border-slate-200/60 rounded-xl p-3 bg-card shadow-card space-y-2.5">
|
||||
<div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
|
||||
<Cpu className="h-3 w-3" /> 公共参数
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">extend</label>
|
||||
<Input value={extend} onChange={e => setExtend(e.target.value)} className="h-8 text-xs" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">netMode</label>
|
||||
<select
|
||||
value={netMode}
|
||||
onChange={e => setNetMode(Number(e.target.value))}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
{NET_MODE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 查询类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('query')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.query ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Radio className="h-3.5 w-3.5 text-primary" />
|
||||
查询类
|
||||
</button>
|
||||
{expandedGroups.query && (
|
||||
<div className="px-3 pb-2.5 space-y-1.5">
|
||||
<CmdBtn label="网络模块开关 (1001)" onClick={() => sendCmd(1001)} />
|
||||
<CmdBtn label="入网状态 (1025)" onClick={() => sendCmd(1025, { netMode })} />
|
||||
<CmdBtn label="功率 (1071)" onClick={() => sendCmd(1071, { netMode })} />
|
||||
<CmdBtn label="频表 (1049)" onClick={() => sendCmd(1049, { netMode })} />
|
||||
<CmdBtn label="频率 (7001)" onClick={() => sendCmd(7001)} />
|
||||
<CmdBtn label="速率 (7003)" onClick={() => sendCmd(7003)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 设置类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('set')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.set ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Settings className="h-3.5 w-3.5 text-amber-500" />
|
||||
设置类
|
||||
</button>
|
||||
{expandedGroups.set && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<CmdBtn label={`网络模块开关 (2001) ctrl=${ctrl}`} onClick={() => sendCmd(2001, { netMode, ctrl })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">ctrl:</span>
|
||||
<select value={ctrl} onChange={e => setCtrl(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
<option value={0}>关</option>
|
||||
<option value={1}>开</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`功率 (2043) power=${power}`} onClick={() => sendCmd(2043, { netMode, power })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">power:</span>
|
||||
<select value={power} onChange={e => setPower(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
{POWER_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`频表 (2023) freqNum=${freqNum}`} onClick={() => sendCmd(2023, { netMode, freqNum })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">freqNum:</span>
|
||||
<Input type="number" min={0} max={20} value={freqNum} onChange={e => setFreqNum(Number(e.target.value))} className="h-7 w-16 text-xs" />
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`频率 (8001) freq=${frequency}MHz`} onClick={() => sendCmd(8001, { frequency })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">frequency:</span>
|
||||
<Input type="number" min={225} max={512} value={frequency} onChange={e => setFrequency(Number(e.target.value))} className="h-7 w-20 text-xs" />
|
||||
<span className="text-xs text-muted-foreground">MHz</span>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`速率 (8003) rate=${rate}`} onClick={() => sendCmd(8003, { rate })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">rate:</span>
|
||||
<select value={rate} onChange={e => setRate(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
{RATE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 上报类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('report')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.report ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Network className="h-3.5 w-3.5 text-emerald-500" />
|
||||
上报类(对接 控制器)
|
||||
</button>
|
||||
{expandedGroups.report && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
在线节点: {ns3Nodes.filter(n => n.status === 'online').length}/{ns3Nodes.length}
|
||||
</span>
|
||||
<Button size="sm" variant="ghost" onClick={fetchNs3Nodes} disabled={ns3Loading} className="h-7 gap-1 text-xs">
|
||||
<RefreshCw className={cn('h-3 w-3', ns3Loading && 'animate-spin')} />
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
<CmdBtn
|
||||
label={`入网断网提示 (5002) state=${ns3Nodes.some(n => n.status === 'online') ? 1 : 0}`}
|
||||
onClick={() => {
|
||||
const state = ns3Nodes.some(n => n.status === 'online') ? 1 : 0;
|
||||
sendCmd(5002, { netMode, state });
|
||||
}}
|
||||
/>
|
||||
<CmdBtn
|
||||
label={`在线信息上报 (5006) IP数=${ns3Nodes.filter(n => n.status === 'online').length}`}
|
||||
onClick={() => {
|
||||
const onlineIps = ns3Nodes.filter(n => n.status === 'online').map(n => n.ip);
|
||||
sendCmd(5006, { netMode, groupMebsIP: onlineIps.length > 0 ? onlineIps : [] });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 上报配置 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('reportCfg')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.reportCfg ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<MessageSquare className="h-3.5 w-3.5 text-violet-500" />
|
||||
上报配置(开关与周期)
|
||||
</button>
|
||||
{expandedGroups.reportCfg && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground w-16 font-mono">5002:</span>
|
||||
<select
|
||||
value={report5002Enabled}
|
||||
onChange={e => setReport5002Enabled(Number(e.target.value))}
|
||||
className="h-7 rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value={1}>开</option>
|
||||
<option value={0}>关</option>
|
||||
</select>
|
||||
<Input
|
||||
type="number"
|
||||
min={500}
|
||||
max={300000}
|
||||
step={100}
|
||||
value={report5002Period}
|
||||
onChange={e => setReport5002Period(Number(e.target.value))}
|
||||
className="h-7 w-20 text-xs"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">ms</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground w-16 font-mono">5006:</span>
|
||||
<select
|
||||
value={report5006Enabled}
|
||||
onChange={e => setReport5006Enabled(Number(e.target.value))}
|
||||
className="h-7 rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value={1}>开</option>
|
||||
<option value={0}>关</option>
|
||||
</select>
|
||||
<Input
|
||||
type="number"
|
||||
min={500}
|
||||
max={300000}
|
||||
step={100}
|
||||
value={report5006Period}
|
||||
onChange={e => setReport5006Period(Number(e.target.value))}
|
||||
className="h-7 w-20 text-xs"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">ms</span>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-1">
|
||||
<CmdBtn label="查询配置 (9001)" onClick={() => sendCmd(9001)} />
|
||||
<CmdBtn label="应用配置 (9003)" onClick={() =>
|
||||
sendCmd(9003, {
|
||||
report5002Enabled, report5002Period,
|
||||
report5006Enabled, report5006Period,
|
||||
})
|
||||
} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧:消息日志 + 自定义发送 */}
|
||||
<div className="flex-1 min-w-0 flex flex-col gap-3">
|
||||
{/* 自定义发送 */}
|
||||
<div className="border border-slate-200/60 rounded-xl p-3 bg-card shadow-card shrink-0">
|
||||
<div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1.5">
|
||||
<MessageSquare className="h-3 w-3" /> 自定义 JSON
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<textarea
|
||||
value={customPayload}
|
||||
onChange={e => setCustomPayload(e.target.value)}
|
||||
placeholder='{"data":{"cmdCode":1001,"extend":"KZ"},...}'
|
||||
className="flex-1 h-16 rounded-lg border bg-background px-3 py-2 text-xs font-mono resize-none focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => { send(customPayload); setCustomPayload(''); }}
|
||||
disabled={!connected || !customPayload.trim()}
|
||||
className="h-16 gap-1.5"
|
||||
>
|
||||
<Send className="h-3.5 w-3.5" />
|
||||
发送
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 消息日志 */}
|
||||
<div className="flex-1 min-h-0 border border-slate-200/60 rounded-xl bg-card shadow-card flex flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-sm font-semibold">消息日志</span>
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4 font-mono">{messages.length}</Badge>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={clearMessages} className="h-7 gap-1.5 text-xs">
|
||||
<Trash2 className="h-3 w-3" />
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
<div ref={scrollRef} className="flex-1 overflow-auto p-3 space-y-1.5 font-mono text-xs">
|
||||
{messages.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center text-muted-foreground py-16">
|
||||
<Wifi className="h-8 w-8 mb-3 opacity-20" />
|
||||
<p>暂无消息,连接后发送命令</p>
|
||||
</div>
|
||||
)}
|
||||
{messages.map(msg => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={cn(
|
||||
'rounded-lg px-3 py-2 border-l-2 transition-colors',
|
||||
msg.direction === 'sent'
|
||||
? 'bg-blue-50/70 border-l-blue-500 dark:bg-blue-950/30'
|
||||
: 'bg-emerald-50/70 border-l-emerald-500 dark:bg-emerald-950/30'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className={cn(
|
||||
'text-[10px] font-bold px-1.5 py-0.5 rounded-md',
|
||||
msg.direction === 'sent' ? 'bg-blue-200 text-blue-800' : 'bg-emerald-200 text-emerald-800'
|
||||
)}>
|
||||
{msg.direction === 'sent' ? '→ 发送' : '← 接收'}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground font-mono">{msg.timestamp}</span>
|
||||
</div>
|
||||
<pre className="whitespace-pre-wrap break-all text-[11px] leading-relaxed">{msg.pretty || msg.payload}</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CmdBtn({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onClick}
|
||||
className="w-full h-8 justify-start text-xs gap-1.5 hover:bg-primary/5 hover:border-primary/30 transition-colors"
|
||||
>
|
||||
<Send className="h-3 w-3 shrink-0 text-primary" />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user