class DataMonitor extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.currentMode = 'udp'; // 默认显示UDP模式
this.udpPort = 54321; // 默认UDP端口
this.udpIp = '127.0.0.1'; // 默认监听所有接口
this.isMonitoring = false; // 监控状态
this.udpData = []; // 存储接收到的UDP数据
// UDP数据注入默认值
this.injectIp = '127.0.0.1';
this.injectPort = 12345;
this.injectData = '{"message": "测试数据"}';
}
connectedCallback() {
this.render();
}
switchMode(mode) {
this.currentMode = mode;
this.render();
}
async startMonitoring() {
if (this.isMonitoring) return;
try {
const response = await fetch('/api/udp-monitor/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
port: this.udpPort,
ip: this.udpIp
}),
});
const data = await response.json();
if (data.success) {
this.isMonitoring = true;
this.updateMonitoringStatus();
this.setupDataFetch();
} else {
this.showError(data.error || '启动监控失败');
}
} catch (error) {
this.showError('无法连接到服务器');
console.error('启动UDP监控失败:', error);
}
}
async stopMonitoring() {
if (!this.isMonitoring) return;
try {
const response = await fetch('/api/udp-monitor/stop', {
method: 'POST',
});
const data = await response.json();
if (data.success) {
this.isMonitoring = false;
this.updateMonitoringStatus();
if (this.dataFetchInterval) {
clearInterval(this.dataFetchInterval);
this.dataFetchInterval = null;
}
} else {
this.showError(data.error || '停止监控失败');
}
} catch (error) {
this.showError('无法连接到服务器');
console.error('停止UDP监控失败:', error);
}
}
async injectUdpData() {
try {
// 验证数据格式
let parsedData;
try {
parsedData = JSON.parse(this.injectData);
} catch (e) {
this.showError('数据格式无效,请输入有效的JSON');
return;
}
const response = await fetch('/api/udp-monitor/inject', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
targetIp: this.injectIp,
targetPort: this.injectPort,
data: parsedData
}),
});
const data = await response.json();
if (data.success) {
this.showSuccess('数据已成功发送');
} else {
this.showError(data.error || '发送数据失败');
}
} catch (error) {
this.showError('无法连接到服务器');
console.error('发送UDP数据失败:', error);
}
}
setupDataFetch() {
// 清除可能存在的之前的定时器
if (this.dataFetchInterval) {
clearInterval(this.dataFetchInterval);
}
// 每秒拉取一次新数据
this.dataFetchInterval = setInterval(async () => {
try {
const response = await fetch('/api/udp-monitor/data');
const data = await response.json();
if (data.success && data.data) {
this.updateDataDisplay(data.data);
}
} catch (error) {
console.error('获取UDP数据失败:', error);
}
}, 1000);
}
updateDataDisplay(newData) {
if (!newData || newData.length === 0) return;
// 更新数据并限制显示的数据条数
this.udpData = [...this.udpData, ...newData].slice(-100);
const dataContainer = this.shadowRoot.querySelector('.data-container');
if (!dataContainer) return;
dataContainer.innerHTML = this.udpData.map(item => {
return `
${new Date(item.timestamp).toLocaleTimeString()}
${item.source}
${this.formatData(item.data)}
`;
}).join('');
// 自动滚动到底部
dataContainer.scrollTop = dataContainer.scrollHeight;
}
formatData(data) {
// 简单显示为字符串,真实实现可能更复杂
if (typeof data === 'object') {
return JSON.stringify(data);
}
return data;
}
updateMonitoringStatus() {
const statusLabel = this.shadowRoot.querySelector('.status-label');
const startButton = this.shadowRoot.querySelector('#start-monitoring');
const stopButton = this.shadowRoot.querySelector('#stop-monitoring');
const portInput = this.shadowRoot.querySelector('#udp-port');
const ipInput = this.shadowRoot.querySelector('#udp-ip');
if (statusLabel) {
statusLabel.textContent = this.isMonitoring ? '监控中' : '未监控';
statusLabel.className = `status-label ${this.isMonitoring ? 'active' : 'inactive'}`;
}
if (startButton) {
startButton.disabled = this.isMonitoring;
}
if (stopButton) {
stopButton.disabled = !this.isMonitoring;
}
if (portInput) {
portInput.disabled = this.isMonitoring;
}
if (ipInput) {
ipInput.disabled = this.isMonitoring;
}
}
showError(message) {
const errorElement = this.shadowRoot.querySelector('.error-message');
if (errorElement) {
errorElement.textContent = message;
errorElement.style.display = 'block';
errorElement.className = 'message-box error-message';
// 3秒后自动隐藏错误消息
setTimeout(() => {
errorElement.style.display = 'none';
}, 3000);
}
}
showSuccess(message) {
const successElement = this.shadowRoot.querySelector('.success-message');
if (successElement) {
successElement.textContent = message;
successElement.style.display = 'block';
// 3秒后自动隐藏成功消息
setTimeout(() => {
successElement.style.display = 'none';
}, 3000);
}
}
render() {
this.shadowRoot.innerHTML = `
${this.currentMode === 'udp'
? `
UDP数据监控
UDP数据注入
`
: `
FastDDS数据监控
FastDDS数据监控内容(待实现)
`}
`;
// 添加切换模式的事件监听
this.shadowRoot.getElementById('udp-mode').addEventListener('click', () => this.switchMode('udp'));
this.shadowRoot.getElementById('fastdds-mode').addEventListener('click', () => this.switchMode('fastdds'));
// 如果是UDP模式,添加控制按钮的事件监听
if (this.currentMode === 'udp') {
// 监控部分事件监听
// IP输入事件
const ipInput = this.shadowRoot.getElementById('udp-ip');
if (ipInput) {
ipInput.addEventListener('change', (e) => {
const value = e.target.value.trim();
// 简单的IP地址验证,可以接受0.0.0.0或具体IP
if (value === '0.0.0.0' || /^(\d{1,3}\.){3}\d{1,3}$/.test(value)) {
this.udpIp = value;
} else {
e.target.value = this.udpIp;
this.showError('请输入有效的IP地址');
}
});
}
// 端口输入事件
const portInput = this.shadowRoot.getElementById('udp-port');
if (portInput) {
portInput.addEventListener('change', (e) => {
const value = parseInt(e.target.value, 10);
if (value >= 1024 && value <= 65535) {
this.udpPort = value;
} else {
e.target.value = this.udpPort;
this.showError('端口号必须在1024-65535之间');
}
});
}
// 开始监控按钮
const startButton = this.shadowRoot.getElementById('start-monitoring');
if (startButton) {
startButton.addEventListener('click', () => this.startMonitoring());
}
// 停止监控按钮
const stopButton = this.shadowRoot.getElementById('stop-monitoring');
if (stopButton) {
stopButton.addEventListener('click', () => this.stopMonitoring());
}
// 数据注入部分事件监听
// 注入IP输入事件
const injectIpInput = this.shadowRoot.getElementById('inject-ip');
if (injectIpInput) {
injectIpInput.addEventListener('change', (e) => {
const value = e.target.value.trim();
if (/^(\d{1,3}\.){3}\d{1,3}$/.test(value)) {
this.injectIp = value;
} else {
e.target.value = this.injectIp;
this.showError('请输入有效的IP地址');
}
});
}
// 注入端口输入事件
const injectPortInput = this.shadowRoot.getElementById('inject-port');
if (injectPortInput) {
injectPortInput.addEventListener('change', (e) => {
const value = parseInt(e.target.value, 10);
if (value >= 1024 && value <= 65535) {
this.injectPort = value;
} else {
e.target.value = this.injectPort;
this.showError('端口号必须在1024-65535之间');
}
});
}
// 注入数据输入事件
const injectDataInput = this.shadowRoot.getElementById('inject-data');
if (injectDataInput) {
injectDataInput.addEventListener('change', (e) => {
this.injectData = e.target.value;
});
}
// 发送数据按钮
const injectButton = this.shadowRoot.getElementById('inject-data-btn');
if (injectButton) {
injectButton.addEventListener('click', () => this.injectUdpData());
}
}
}
}
customElements.define('data-monitor', DataMonitor);