up
This commit is contained in:
@@ -0,0 +1,233 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>meshgo MQTT 管理面板</title>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; }
|
||||||
|
header { background: #1677ff; color: #fff; padding: 16px 24px; font-size: 18px; font-weight: 600; }
|
||||||
|
.container { max-width: 1200px; margin: 24px auto; padding: 0 16px; }
|
||||||
|
|
||||||
|
/* 指标卡片 */
|
||||||
|
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
|
||||||
|
.card { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
||||||
|
.card .label { font-size: 13px; color: #888; margin-bottom: 6px; }
|
||||||
|
.card .value { font-size: 28px; font-weight: 700; color: #1677ff; }
|
||||||
|
.card .sub { font-size: 12px; color: #aaa; margin-top: 4px; }
|
||||||
|
|
||||||
|
/* 图表区 */
|
||||||
|
.charts { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
|
||||||
|
.chart-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
||||||
|
.chart-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
|
||||||
|
.chart-wrap { position: relative; height: 220px; }
|
||||||
|
|
||||||
|
/* 客户端表格 */
|
||||||
|
.table-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
||||||
|
.table-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th { text-align: left; padding: 10px 12px; background: #fafafa; border-bottom: 1px solid #eee; font-size: 13px; color: #666; }
|
||||||
|
td { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; font-size: 13px; }
|
||||||
|
tr:hover td { background: #fafafa; }
|
||||||
|
.online-dot { display: inline-block; width: 8px; height: 8px; background: #52c41a; border-radius: 50%; margin-right: 6px; }
|
||||||
|
.tag { display: inline-block; padding: 2px 8px; background: #e6f4ff; color: #1677ff; border-radius: 4px; font-size: 12px; margin: 1px; }
|
||||||
|
.refresh-info { font-size: 12px; color: #aaa; text-align: right; margin-top: 8px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>meshgo MQTT 管理面板</header>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
|
||||||
|
<!-- 指标卡片 -->
|
||||||
|
<div class="cards">
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">当前连接</div>
|
||||||
|
<div class="value" id="connections">-</div>
|
||||||
|
<div class="sub">实时在线客户端数</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">累计消息</div>
|
||||||
|
<div class="value" id="messages_total">-</div>
|
||||||
|
<div class="sub">所有主题消息总数</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">msh/# 消息</div>
|
||||||
|
<div class="value" id="messages_msh">-</div>
|
||||||
|
<div class="sub">mesh 主题消息数</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">运行时长</div>
|
||||||
|
<div class="value" id="uptime">-</div>
|
||||||
|
<div class="sub" id="uptime_sub">-</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 图表 -->
|
||||||
|
<div class="charts">
|
||||||
|
<div class="chart-box">
|
||||||
|
<h3>消息趋势(最近 30 条)</h3>
|
||||||
|
<div class="chart-wrap"><canvas id="trendChart"></canvas></div>
|
||||||
|
</div>
|
||||||
|
<div class="chart-box">
|
||||||
|
<h3>主题分布</h3>
|
||||||
|
<div class="chart-wrap"><canvas id="topicChart"></canvas></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 在线客户端 -->
|
||||||
|
<div class="table-box">
|
||||||
|
<h3>在线客户端 <span id="client_count" style="font-weight:normal;font-size:13px;color:#888"></span></h3>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>状态</th>
|
||||||
|
<th>客户端 ID</th>
|
||||||
|
<th>IP 地址</th>
|
||||||
|
<th>用户名</th>
|
||||||
|
<th>订阅数</th>
|
||||||
|
<th>连接时间</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="clients_tbody">
|
||||||
|
<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无数据</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div class="refresh-info">每 3 秒自动刷新</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 消息趋势环形缓冲
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
const MAX_TREND = 30;
|
||||||
|
const trendBuffer = [];
|
||||||
|
let trendLabels = [];
|
||||||
|
let trendData = [];
|
||||||
|
|
||||||
|
const trendCtx = document.getElementById('trendChart').getContext('2d');
|
||||||
|
const trendChart = new Chart(trendCtx, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: trendLabels,
|
||||||
|
datasets: [{
|
||||||
|
label: '消息数',
|
||||||
|
data: trendData,
|
||||||
|
borderColor: '#1677ff',
|
||||||
|
backgroundColor: 'rgba(22,119,255,0.1)',
|
||||||
|
fill: true,
|
||||||
|
tension: 0.3,
|
||||||
|
pointRadius: 3,
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
animation: false,
|
||||||
|
scales: {
|
||||||
|
x: { display: false },
|
||||||
|
y: { beginAtZero: true, ticks: { stepSize: 1 } }
|
||||||
|
},
|
||||||
|
plugins: { legend: { display: false } }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const topicCtx = document.getElementById('topicChart').getContext('2d');
|
||||||
|
const topicChart = new Chart(topicCtx, {
|
||||||
|
type: 'bar',
|
||||||
|
data: { labels: [], datasets: [{ label: '消息数', data: [], backgroundColor: '#1677ff' }] },
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
animation: false,
|
||||||
|
plugins: { legend: { display: false } },
|
||||||
|
scales: {
|
||||||
|
x: { ticks: { maxRotation: 45, minRotation: 45, font: { size: 11 } } },
|
||||||
|
y: { beginAtZero: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let lastTotal = 0;
|
||||||
|
|
||||||
|
function formatUptime(s) {
|
||||||
|
if (s < 60) return s + ' 秒';
|
||||||
|
if (s < 3600) return Math.floor(s/60) + ' 分 ' + (s%60) + ' 秒';
|
||||||
|
const h = Math.floor(s/3600);
|
||||||
|
const m = Math.floor((s%3600)/60);
|
||||||
|
const sec = s%60;
|
||||||
|
return h + ' 小时 ' + m + ' 分 ' + sec + ' 秒';
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchStats() {
|
||||||
|
fetch('/admin/mqtt/api/stats')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(res => {
|
||||||
|
const d = res.data;
|
||||||
|
|
||||||
|
// 指标卡片
|
||||||
|
document.getElementById('connections').textContent = d.connections;
|
||||||
|
document.getElementById('messages_total').textContent = d.messages_total;
|
||||||
|
document.getElementById('messages_msh').textContent = d.messages_msh;
|
||||||
|
document.getElementById('uptime').textContent = formatUptime(d.uptime);
|
||||||
|
document.getElementById('uptime_sub').textContent = '服务已运行 ' + formatUptime(d.uptime);
|
||||||
|
|
||||||
|
// 趋势图(增量)
|
||||||
|
const delta = d.messages_total - lastTotal;
|
||||||
|
lastTotal = d.messages_total;
|
||||||
|
trendBuffer.push(delta);
|
||||||
|
if (trendBuffer.length > MAX_TREND) trendBuffer.shift();
|
||||||
|
trendLabels.length = 0;
|
||||||
|
trendLabels.push(...trendBuffer.map((_, i) => ''));
|
||||||
|
trendData.length = 0;
|
||||||
|
trendData.push(...trendBuffer);
|
||||||
|
trendChart.data.labels = trendLabels;
|
||||||
|
trendChart.data.datasets[0].data = trendData;
|
||||||
|
trendChart.update();
|
||||||
|
|
||||||
|
// 主题分布
|
||||||
|
const topics = d.topics || {};
|
||||||
|
const sorted = Object.entries(topics).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
||||||
|
topicChart.data.labels = sorted.map(x => x[0]);
|
||||||
|
topicChart.data.datasets[0].data = sorted.map(x => x[1]);
|
||||||
|
topicChart.update();
|
||||||
|
|
||||||
|
// 客户端表格
|
||||||
|
document.getElementById('client_count').textContent = '(' + d.clients.length + ')';
|
||||||
|
const tbody = document.getElementById('clients_tbody');
|
||||||
|
if (!d.clients || d.clients.length === 0) {
|
||||||
|
tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无在线客户端</td></tr>';
|
||||||
|
} else {
|
||||||
|
tbody.innerHTML = d.clients.map(c => {
|
||||||
|
const time = new Date(c.connected_at).toLocaleString('zh-CN', { hour12: false });
|
||||||
|
return `<tr>
|
||||||
|
<td><span class="online-dot"></span>在线</td>
|
||||||
|
<td><a href="/admin/mqtt/client/${esc(c.id)}" style="color:#1677ff;text-decoration:none">${esc(c.id)}</a></td>
|
||||||
|
<td>${esc(c.remote_addr)}</td>
|
||||||
|
<td>${esc(c.username)}</td>
|
||||||
|
<td>${c.subs_count}</td>
|
||||||
|
<td>${time}</td>
|
||||||
|
</tr>`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
if (!s) return '';
|
||||||
|
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 每 3 秒刷新
|
||||||
|
fetchStats();
|
||||||
|
setInterval(fetchStats, 3000);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>客户端详情 - meshgo</title>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; }
|
||||||
|
header { background: #1677ff; color: #fff; padding: 16px 24px; font-size: 18px; font-weight: 600; display: flex; align-items: center; gap: 12px; }
|
||||||
|
.back-btn { color: #fff; text-decoration: none; font-size: 14px; opacity: 0.8; }
|
||||||
|
.back-btn:hover { opacity: 1; }
|
||||||
|
.container { max-width: 1000px; margin: 24px auto; padding: 0 16px; }
|
||||||
|
|
||||||
|
.card { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); margin-bottom: 16px; }
|
||||||
|
.card h3 { font-size: 15px; color: #333; margin-bottom: 16px; border-bottom: 1px solid #eee; padding-bottom: 10px; }
|
||||||
|
.info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
|
||||||
|
.info-item { }
|
||||||
|
.info-item .label { font-size: 12px; color: #888; margin-bottom: 4px; }
|
||||||
|
.info-item .value { font-size: 14px; color: #333; font-weight: 500; }
|
||||||
|
|
||||||
|
.sub-list { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.sub-tag { display: inline-block; padding: 4px 12px; background: #e6f4ff; color: #1677ff; border-radius: 4px; font-size: 13px; font-family: monospace; }
|
||||||
|
|
||||||
|
.online-dot { display: inline-block; width: 8px; height: 8px; background: #52c41a; border-radius: 50%; margin-right: 6px; }
|
||||||
|
.status-online { color: #52c41a; }
|
||||||
|
.status-offline { color: #ff4d4f; }
|
||||||
|
|
||||||
|
.loading, .error, .not-found { text-align: center; padding: 48px; color: #888; }
|
||||||
|
.error { color: #ff4d4f; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>
|
||||||
|
<a href="/admin/mqtt" class="back-btn">← 返回</a>
|
||||||
|
客户端详情
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<div id="app">
|
||||||
|
<div class="loading">加载中...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const clientId = window.location.pathname.split('/').pop();
|
||||||
|
|
||||||
|
function renderClient(client, subs) {
|
||||||
|
if (!client) {
|
||||||
|
document.getElementById('app').innerHTML = '<div class="card"><div class="not-found">客户端不存在或已离线</div></div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const time = new Date(client.connected_at).toLocaleString('zh-CN', { hour12: false });
|
||||||
|
const subsHtml = subs.length > 0
|
||||||
|
? subs.map(s => `<span class="sub-tag">${esc(s)}</span>`).join('')
|
||||||
|
: '<span style="color:#aaa">暂无订阅</span>';
|
||||||
|
|
||||||
|
document.getElementById('app').innerHTML = `
|
||||||
|
<div class="card">
|
||||||
|
<h3>基本信息</h3>
|
||||||
|
<div class="info-grid">
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">状态</div>
|
||||||
|
<div class="value"><span class="online-dot"></span><span class="status-online">在线</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">客户端 ID</div>
|
||||||
|
<div class="value" style="font-family:monospace;font-size:13px">${esc(client.id)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">IP 地址</div>
|
||||||
|
<div class="value">${esc(client.remote_addr)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">用户名</div>
|
||||||
|
<div class="value">${esc(client.username)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">连接时间</div>
|
||||||
|
<div class="value">${time}</div>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<div class="label">订阅数</div>
|
||||||
|
<div class="value">${client.subs_count}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h3>订阅主题 (${subs.length})</h3>
|
||||||
|
<div class="sub-list">${subsHtml}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
if (!s) return '';
|
||||||
|
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||||
|
}
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
Promise.all([
|
||||||
|
fetch('/admin/mqtt/api/client/' + encodeURIComponent(clientId)).then(r => r.json()),
|
||||||
|
fetch('/admin/mqtt/api/client/' + encodeURIComponent(clientId) + '/subs').then(r => r.json())
|
||||||
|
]).then(([clientRes, subsRes]) => {
|
||||||
|
if (clientRes.code !== 0) {
|
||||||
|
document.getElementById('app').innerHTML = '<div class="card"><div class="error">获取客户端信息失败</div></div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
renderClient(clientRes.data, subsRes.data || []);
|
||||||
|
}).catch(() => {
|
||||||
|
document.getElementById('app').innerHTML = '<div class="card"><div class="error">网络错误</div></div>';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
load();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+116
-17
@@ -36,9 +36,19 @@ func New(cfg *config.AdminConfig) *Server {
|
|||||||
{
|
{
|
||||||
admin.GET("/api/stats", handleStats)
|
admin.GET("/api/stats", handleStats)
|
||||||
admin.GET("/api/clients", handleClients)
|
admin.GET("/api/clients", handleClients)
|
||||||
|
admin.GET("/api/client/:id", handleClientDetail)
|
||||||
|
admin.GET("/api/client/:id/subs", handleClientSubs)
|
||||||
|
}
|
||||||
|
r.GET("/admin/mqtt", serveAdmin)
|
||||||
|
r.GET("/admin/mqtt/client/:id", serveClientDetail)
|
||||||
|
r.GET("/", serveIndex)
|
||||||
|
|
||||||
|
// Meshtastic 消息查看
|
||||||
|
meshtastic := r.Group("/admin/meshtastic")
|
||||||
|
{
|
||||||
|
meshtastic.GET("/", serveMeshtastic)
|
||||||
|
meshtastic.GET("/api/messages", handleMessages)
|
||||||
}
|
}
|
||||||
r.GET("/admin/mqtt", serveIndex)
|
|
||||||
r.GET("/", serveHome)
|
|
||||||
|
|
||||||
addr := cfg.Port
|
addr := cfg.Port
|
||||||
if addr == "" {
|
if addr == "" {
|
||||||
@@ -90,23 +100,76 @@ func (s *Server) Enabled() bool { return s.enabled }
|
|||||||
// serveIndex 返回管理页面
|
// serveIndex 返回管理页面
|
||||||
func serveIndex(c *gin.Context) {
|
func serveIndex(c *gin.Context) {
|
||||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||||
c.String(http.StatusOK, indexHTML)
|
c.String(http.StatusOK, homeHTML)
|
||||||
}
|
}
|
||||||
|
|
||||||
// serveHome 主页(meshmap 占位)
|
// serveAdmin MQTT 管理页面
|
||||||
func serveHome(c *gin.Context) {
|
func serveAdmin(c *gin.Context) {
|
||||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||||
c.String(http.StatusOK, `<!DOCTYPE html>
|
c.String(http.StatusOK, adminHTML)
|
||||||
<html lang="zh-CN">
|
}
|
||||||
<head><meta charset="UTF-8"><title>meshgo</title></head>
|
|
||||||
<body style="font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f0f2f5">
|
// serveClientDetail 客户端详情页面
|
||||||
<div style="text-align:center">
|
func serveClientDetail(c *gin.Context) {
|
||||||
<h1 style="font-size:48px;color:#1677ff;margin-bottom:8px">meshmap</h1>
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||||
<p style="color:#888;margin-bottom:24px">Mesh Network Map · 网格拓扑可视化</p>
|
c.String(http.StatusOK, clientDetailHTML)
|
||||||
<a href="/admin/mqtt" style="display:inline-block;padding:10px 24px;background:#1677ff;color:#fff;text-decoration:none;border-radius:6px;font-size:14px">MQTT 管理面板</a>
|
}
|
||||||
</div>
|
|
||||||
</body>
|
// serveMeshtastic Meshtastic 消息查看页面
|
||||||
</html>`)
|
func serveMeshtastic(c *gin.Context) {
|
||||||
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||||
|
c.String(http.StatusOK, meshtasticHTML)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleMessages 返回 msh 消息列表(JSON)
|
||||||
|
func handleMessages(c *gin.Context) {
|
||||||
|
messages := stats.GetMessages()
|
||||||
|
pskIndex := stats.GetDefaultPSKIndex()
|
||||||
|
|
||||||
|
for i := range messages {
|
||||||
|
if isJsonTopic(messages[i].Topic) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
dec, err := stats.TryDecryptMessage(messages[i].Payload, pskIndex)
|
||||||
|
if err != nil {
|
||||||
|
// 打印详细错误
|
||||||
|
env, parseErr := stats.ParseServiceEnvelopeDebug(messages[i].Payload)
|
||||||
|
if parseErr != nil {
|
||||||
|
log.Printf("[decrypt] FAIL psk=%d topic=%s parse_err=%v decrypt_err=%v payload_len=%d",
|
||||||
|
pskIndex, messages[i].Topic, parseErr, err, len(messages[i].Payload))
|
||||||
|
} else {
|
||||||
|
packetId := uint64(0)
|
||||||
|
from := uint32(0)
|
||||||
|
variant := 0
|
||||||
|
encryptedLen := 0
|
||||||
|
if env.Packet != nil {
|
||||||
|
packetId = env.Packet.Id
|
||||||
|
from = env.Packet.From
|
||||||
|
variant = env.Packet.WhichPayloadVariant
|
||||||
|
encryptedLen = len(env.Packet.Encrypted)
|
||||||
|
}
|
||||||
|
log.Printf("[decrypt] FAIL psk=%d topic=%s channel=%s packetId=%d from=0x%x variant=%d encrypted_len=%d err=%v",
|
||||||
|
pskIndex, messages[i].Topic, env.ChannelId, packetId, from, variant, encryptedLen, err)
|
||||||
|
}
|
||||||
|
messages[i].Decrypted = &stats.DecryptedMessage{
|
||||||
|
GatewayId: err.Error(),
|
||||||
|
}
|
||||||
|
} else if dec != nil {
|
||||||
|
messages[i].Decrypted = dec
|
||||||
|
log.Printf("[decrypt] OK topic=%s channel=%s packetId=%d from=0x%x port=%d payload_len=%d",
|
||||||
|
messages[i].Topic, dec.ChannelId, dec.PacketId, dec.From, dec.PortNum, len(dec.Payload))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"code": 0,
|
||||||
|
"data": messages,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func isJsonTopic(topic string) bool {
|
||||||
|
return len(topic) > 0 && (topic[len(topic)-1] == 'n' || topic[len(topic)-5:len(topic)] == "/json")
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleStats 返回实时统计(JSON)
|
// handleStats 返回实时统计(JSON)
|
||||||
@@ -126,6 +189,33 @@ func handleClients(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleClientDetail 返回指定客户端详情(JSON)
|
||||||
|
func handleClientDetail(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
info := stats.GetClient(id)
|
||||||
|
if info == nil {
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"code": 404,
|
||||||
|
"msg": "客户端不存在或已离线",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"code": 0,
|
||||||
|
"data": info,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleClientSubs 返回指定客户端的订阅主题列表(JSON)
|
||||||
|
func handleClientSubs(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
subs := stats.GetClientSubs(id)
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"code": 0,
|
||||||
|
"data": subs,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 认证中间件(预留扩展点)
|
// 认证中间件(预留扩展点)
|
||||||
// AuthMiddleware 根据 cfg.AuthType 选择对应认证策略
|
// AuthMiddleware 根据 cfg.AuthType 选择对应认证策略
|
||||||
@@ -168,4 +258,13 @@ func basicAuth(user, pass string) gin.HandlerFunc {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
//go:embed index.html
|
//go:embed index.html
|
||||||
var indexHTML string
|
var homeHTML string
|
||||||
|
|
||||||
|
//go:embed admin_mqtt.html
|
||||||
|
var adminHTML string
|
||||||
|
|
||||||
|
//go:embed client_detail.html
|
||||||
|
var clientDetailHTML string
|
||||||
|
|
||||||
|
//go:embed meshtastic.html
|
||||||
|
var meshtasticHTML string
|
||||||
|
|||||||
+6
-232
@@ -1,237 +1,11 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head><meta charset="UTF-8"><title>meshgo</title></head>
|
||||||
<meta charset="UTF-8">
|
<body style="font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f0f2f5">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<div style="text-align:center">
|
||||||
<title>meshgo 管理面板</title>
|
<h1 style="font-size:48px;color:#1677ff;margin-bottom:8px">meshmap</h1>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
<p style="color:#888;margin-bottom:24px">Mesh Network Map · 网格拓扑可视化</p>
|
||||||
<style>
|
<a href="/admin/mqtt" style="display:inline-block;padding:10px 24px;background:#1677ff;color:#fff;text-decoration:none;border-radius:6px;font-size:14px">MQTT 管理面板</a>
|
||||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
||||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; }
|
|
||||||
header { background: #1677ff; color: #fff; padding: 16px 24px; font-size: 18px; font-weight: 600; }
|
|
||||||
.container { max-width: 1200px; margin: 24px auto; padding: 0 16px; }
|
|
||||||
|
|
||||||
/* 指标卡片 */
|
|
||||||
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
|
|
||||||
.card { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
|
||||||
.card .label { font-size: 13px; color: #888; margin-bottom: 6px; }
|
|
||||||
.card .value { font-size: 28px; font-weight: 700; color: #1677ff; }
|
|
||||||
.card .sub { font-size: 12px; color: #aaa; margin-top: 4px; }
|
|
||||||
|
|
||||||
/* 图表区 */
|
|
||||||
.charts { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
|
|
||||||
.chart-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
|
||||||
.chart-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
|
|
||||||
.chart-wrap { position: relative; height: 220px; }
|
|
||||||
|
|
||||||
/* 客户端表格 */
|
|
||||||
.table-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
|
|
||||||
.table-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
|
|
||||||
table { width: 100%; border-collapse: collapse; }
|
|
||||||
th { text-align: left; padding: 10px 12px; background: #fafafa; border-bottom: 1px solid #eee; font-size: 13px; color: #666; }
|
|
||||||
td { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; font-size: 13px; }
|
|
||||||
tr:hover td { background: #fafafa; }
|
|
||||||
.online-dot { display: inline-block; width: 8px; height: 8px; background: #52c41a; border-radius: 50%; margin-right: 6px; }
|
|
||||||
.tag { display: inline-block; padding: 2px 8px; background: #e6f4ff; color: #1677ff; border-radius: 4px; font-size: 12px; margin: 1px; }
|
|
||||||
.refresh-info { font-size: 12px; color: #aaa; text-align: right; margin-top: 8px; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
|
|
||||||
<header>meshgo MQTT 管理面板</header>
|
|
||||||
|
|
||||||
<div class="container">
|
|
||||||
|
|
||||||
<!-- 指标卡片 -->
|
|
||||||
<div class="cards">
|
|
||||||
<div class="card">
|
|
||||||
<div class="label">当前连接</div>
|
|
||||||
<div class="value" id="connections">-</div>
|
|
||||||
<div class="sub">实时在线客户端数</div>
|
|
||||||
</div>
|
|
||||||
<div class="card">
|
|
||||||
<div class="label">累计消息</div>
|
|
||||||
<div class="value" id="messages_total">-</div>
|
|
||||||
<div class="sub">所有主题消息总数</div>
|
|
||||||
</div>
|
|
||||||
<div class="card">
|
|
||||||
<div class="label">msh/# 消息</div>
|
|
||||||
<div class="value" id="messages_msh">-</div>
|
|
||||||
<div class="sub">mesh 主题消息数</div>
|
|
||||||
</div>
|
|
||||||
<div class="card">
|
|
||||||
<div class="label">运行时长</div>
|
|
||||||
<div class="value" id="uptime">-</div>
|
|
||||||
<div class="sub" id="uptime_sub">-</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 图表 -->
|
|
||||||
<div class="charts">
|
|
||||||
<div class="chart-box">
|
|
||||||
<h3>消息趋势(最近 30 条)</h3>
|
|
||||||
<div class="chart-wrap"><canvas id="trendChart"></canvas></div>
|
|
||||||
</div>
|
|
||||||
<div class="chart-box">
|
|
||||||
<h3>主题分布</h3>
|
|
||||||
<div class="chart-wrap"><canvas id="topicChart"></canvas></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 在线客户端 -->
|
|
||||||
<div class="table-box">
|
|
||||||
<h3>在线客户端 <span id="client_count" style="font-weight:normal;font-size:13px;color:#888"></span></h3>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>状态</th>
|
|
||||||
<th>客户端 ID</th>
|
|
||||||
<th>IP 地址</th>
|
|
||||||
<th>用户名</th>
|
|
||||||
<th>订阅数</th>
|
|
||||||
<th>连接时间</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="clients_tbody">
|
|
||||||
<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无数据</td></tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<div class="refresh-info">每 3 秒自动刷新</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// 消息趋势环形缓冲
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
const MAX_TREND = 30;
|
|
||||||
const trendBuffer = [];
|
|
||||||
let trendLabels = [];
|
|
||||||
let trendData = [];
|
|
||||||
|
|
||||||
const trendCtx = document.getElementById('trendChart').getContext('2d');
|
|
||||||
const trendChart = new Chart(trendCtx, {
|
|
||||||
type: 'line',
|
|
||||||
data: {
|
|
||||||
labels: trendLabels,
|
|
||||||
datasets: [{
|
|
||||||
label: '消息数',
|
|
||||||
data: trendData,
|
|
||||||
borderColor: '#1677ff',
|
|
||||||
backgroundColor: 'rgba(22,119,255,0.1)',
|
|
||||||
fill: true,
|
|
||||||
tension: 0.3,
|
|
||||||
pointRadius: 3,
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
animation: false,
|
|
||||||
scales: {
|
|
||||||
x: { display: false },
|
|
||||||
y: { beginAtZero: true, ticks: { stepSize: 1 } }
|
|
||||||
},
|
|
||||||
plugins: { legend: { display: false } }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const topicCtx = document.getElementById('topicChart').getContext('2d');
|
|
||||||
const topicChart = new Chart(topicCtx, {
|
|
||||||
type: 'bar',
|
|
||||||
data: { labels: [], datasets: [{ label: '消息数', data: [], backgroundColor: '#1677ff' }] },
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
animation: false,
|
|
||||||
plugins: { legend: { display: false } },
|
|
||||||
scales: {
|
|
||||||
x: { ticks: { maxRotation: 45, minRotation: 45, font: { size: 11 } } },
|
|
||||||
y: { beginAtZero: true }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let lastTotal = 0;
|
|
||||||
|
|
||||||
function formatUptime(s) {
|
|
||||||
if (s < 60) return s + ' 秒';
|
|
||||||
if (s < 3600) return Math.floor(s/60) + ' 分 ' + (s%60) + ' 秒';
|
|
||||||
const h = Math.floor(s/3600);
|
|
||||||
const m = Math.floor((s%3600)/60);
|
|
||||||
const sec = s%60;
|
|
||||||
return h + ' 小时 ' + m + ' 分 ' + sec + ' 秒';
|
|
||||||
}
|
|
||||||
|
|
||||||
function fetchStats() {
|
|
||||||
fetch('/admin/mqtt/api/stats')
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(res => {
|
|
||||||
const d = res.data;
|
|
||||||
|
|
||||||
// 指标卡片
|
|
||||||
document.getElementById('connections').textContent = d.connections;
|
|
||||||
document.getElementById('messages_total').textContent = d.messages_total;
|
|
||||||
document.getElementById('messages_msh').textContent = d.messages_msh;
|
|
||||||
document.getElementById('uptime').textContent = formatUptime(d.uptime);
|
|
||||||
document.getElementById('uptime_sub').textContent = '服务已运行 ' + formatUptime(d.uptime);
|
|
||||||
|
|
||||||
// 趋势图(增量)
|
|
||||||
const delta = d.messages_total - lastTotal;
|
|
||||||
lastTotal = d.messages_total;
|
|
||||||
trendBuffer.push(delta);
|
|
||||||
if (trendBuffer.length > MAX_TREND) trendBuffer.shift();
|
|
||||||
const now = new Date();
|
|
||||||
trendLabels.length = 0;
|
|
||||||
trendLabels.push(...trendBuffer.map((_, i) => ''));
|
|
||||||
trendData.length = 0;
|
|
||||||
trendData.push(...trendBuffer);
|
|
||||||
trendChart.data.labels = trendLabels;
|
|
||||||
trendChart.data.datasets[0].data = trendData;
|
|
||||||
trendChart.update();
|
|
||||||
|
|
||||||
// 主题分布
|
|
||||||
const topics = d.topics || {};
|
|
||||||
const sorted = Object.entries(topics).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
|
||||||
topicChart.data.labels = sorted.map(x => x[0]);
|
|
||||||
topicChart.data.datasets[0].data = sorted.map(x => x[1]);
|
|
||||||
topicChart.update();
|
|
||||||
|
|
||||||
// 客户端表格
|
|
||||||
document.getElementById('client_count').textContent = '(' + d.clients.length + ')';
|
|
||||||
const tbody = document.getElementById('clients_tbody');
|
|
||||||
if (!d.clients || d.clients.length === 0) {
|
|
||||||
tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无在线客户端</td></tr>';
|
|
||||||
} else {
|
|
||||||
tbody.innerHTML = d.clients.map(c => {
|
|
||||||
const subs = c.subs_count > 0
|
|
||||||
? Array(Math.min(c.subs_count, 5)).fill('<span class="tag">...</span>').join('')
|
|
||||||
: '-';
|
|
||||||
const time = new Date(c.connected_at).toLocaleString('zh-CN', { hour12: false });
|
|
||||||
return `<tr>
|
|
||||||
<td><span class="online-dot"></span>在线</td>
|
|
||||||
<td>${esc(c.id)}</td>
|
|
||||||
<td>${esc(c.remote_addr)}</td>
|
|
||||||
<td>${esc(c.username)}</td>
|
|
||||||
<td>${c.subs_count}</td>
|
|
||||||
<td>${time}</td>
|
|
||||||
</tr>`;
|
|
||||||
}).join('');
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function esc(s) {
|
|
||||||
if (!s) return '';
|
|
||||||
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 每 3 秒刷新
|
|
||||||
fetchStats();
|
|
||||||
setInterval(fetchStats, 3000);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,269 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Meshtastic 消息 - meshgo</title>
|
||||||
|
<style>
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; }
|
||||||
|
header { background: #1677ff; color: #fff; padding: 16px 24px; font-size: 18px; font-weight: 600; display: flex; align-items: center; gap: 12px; }
|
||||||
|
.back-btn { color: #fff; text-decoration: none; font-size: 14px; opacity: 0.8; }
|
||||||
|
.back-btn:hover { opacity: 1; }
|
||||||
|
.container { max-width: 1400px; margin: 24px auto; padding: 0 16px; }
|
||||||
|
|
||||||
|
.toolbar { background: #fff; border-radius: 8px; padding: 16px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,.08); display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.toolbar label { font-size: 14px; color: #666; }
|
||||||
|
.toolbar .count { margin-left: auto; font-size: 14px; color: #666; }
|
||||||
|
.refresh-info { font-size: 12px; color: #aaa; text-align: right; margin-top: 8px; padding: 0 20px 16px; }
|
||||||
|
|
||||||
|
.msg-list { background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.08); overflow: hidden; }
|
||||||
|
.msg-item { padding: 14px 20px; border-bottom: 1px solid #f0f0f0; }
|
||||||
|
.msg-item:last-child { border-bottom: none; }
|
||||||
|
.msg-item:hover { background: #fafafa; }
|
||||||
|
.msg-item.encrypted { background: #fffbe6; }
|
||||||
|
.msg-item.encrypted:hover { background: #fff7cc; }
|
||||||
|
.msg-item.decrypted { background: #f6ffed; }
|
||||||
|
.msg-item.decrypted:hover { background: #d9f7be; }
|
||||||
|
.msg-item.json { background: #e6f4ff; }
|
||||||
|
.msg-item.json:hover { background: #bae0ff; }
|
||||||
|
|
||||||
|
.msg-header { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
|
||||||
|
.msg-time { font-size: 12px; color: #888; font-family: monospace; }
|
||||||
|
.msg-topic { font-size: 13px; color: #1677ff; font-family: monospace; }
|
||||||
|
.badge { font-size: 11px; padding: 2px 6px; border-radius: 4px; font-weight: 500; }
|
||||||
|
.badge-json { background: #1677ff; color: #fff; }
|
||||||
|
.badge-dec { background: #52c41a; color: #fff; }
|
||||||
|
.badge-enc { background: #fa8c16; color: #fff; }
|
||||||
|
.badge-err { background: #ff4d4f; color: #fff; }
|
||||||
|
|
||||||
|
.msg-meta { display: flex; gap: 16px; font-size: 12px; color: #666; margin-bottom: 8px; }
|
||||||
|
.msg-meta span { display: flex; align-items: center; gap: 4px; }
|
||||||
|
.msg-meta .label { color: #999; }
|
||||||
|
|
||||||
|
.msg-payload { font-family: monospace; font-size: 13px; color: #333; background: #f5f5f5; padding: 10px 12px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; max-height: 300px; overflow-y: auto; }
|
||||||
|
.msg-payload.decrypted { background: #f6ffed; border: 1px solid #b7eb8f; }
|
||||||
|
.msg-payload.hex { background: #f0f5ff; border: 1px solid #adc6ff; color: #333; }
|
||||||
|
|
||||||
|
.port-badge { font-size: 11px; padding: 2px 6px; border-radius: 4px; background: #13c2c2; color: #fff; }
|
||||||
|
|
||||||
|
.empty { text-align: center; padding: 48px; color: #aaa; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>
|
||||||
|
<a href="/admin/mqtt" class="back-btn">← 返回</a>
|
||||||
|
Meshtastic 消息监控
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<div class="toolbar">
|
||||||
|
<span class="count" id="count">共 0 条消息</span>
|
||||||
|
<span class="refresh-info">每 3 秒自动刷新 | 使用默认 PSK 解密</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="msg-list" id="msgList">
|
||||||
|
<div class="empty">暂无消息,等待数据...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// PortNum 名称映射
|
||||||
|
const portNames = {
|
||||||
|
0: 'Reserved', 1: 'TEXT', 2: 'REMOTE_HW', 3: 'POSITION',
|
||||||
|
4: 'NODEINFO', 5: 'ROUTING', 6: 'ADMIN', 7: 'TEXT2',
|
||||||
|
8: 'WAYPOINT', 9: 'WIFI', 10: 'MXT_AI', 11: 'RANGE_TEST',
|
||||||
|
12: 'DETECTION', 13: 'REPLY', 14: 'IP_TUNNEL', 15: 'SERIAL',
|
||||||
|
16: 'STORE_FWD', 17: 'TELEMETRY', 18: 'ZPS', 19: 'SIMULATOR',
|
||||||
|
20: 'TRACEROUTE', 21: 'NEIGHBOR', 22: 'AUDIO', 23: 'DUPLICATE',
|
||||||
|
24: 'ACK', 25: 'CONFIG', 26: 'IPLY_CONFIG', 27: 'MAP_REPORT',
|
||||||
|
28: 'PaxCounter', 32: 'PRIVATE', 256: 'ATAK', 257: 'HALP',
|
||||||
|
258: 'RPC', 259: 'XMPP', 260: 'STREAM', 261: 'TUNNEL'
|
||||||
|
};
|
||||||
|
|
||||||
|
function getPortName(num) {
|
||||||
|
return portNames[num] || `Port#${num}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
if (!s) return '';
|
||||||
|
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(ts) {
|
||||||
|
const d = new Date(ts);
|
||||||
|
return d.toLocaleString('zh-CN', {
|
||||||
|
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||||
|
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function hexToText(hex) {
|
||||||
|
try {
|
||||||
|
// 尝试将十六进制字符串转换为文本
|
||||||
|
const bytes = new Uint8Array(hex.match(/.{2}/g).map(b => parseInt(b, 16)));
|
||||||
|
// 检查是否包含 UTF-8 可打印字符
|
||||||
|
let printable = '';
|
||||||
|
let allPrintable = true;
|
||||||
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
|
const c = bytes[i];
|
||||||
|
if (c >= 32 && c < 127) {
|
||||||
|
printable += String.fromCharCode(c);
|
||||||
|
} else if (c >= 0xC0 || (c >= 0x80 && printable.length > 0)) {
|
||||||
|
// UTF-8 多字节字符
|
||||||
|
printable += String.fromCharCode(c);
|
||||||
|
} else if (c === 0) {
|
||||||
|
printable += ' ';
|
||||||
|
} else {
|
||||||
|
allPrintable = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (allPrintable) return printable.trim();
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBytes(data) {
|
||||||
|
if (data instanceof Uint8Array) return data;
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
// 可能是 base64 字符串
|
||||||
|
const raw = atob(data);
|
||||||
|
return new Uint8Array([...raw].map(c => c.charCodeAt(0)));
|
||||||
|
}
|
||||||
|
return new Uint8Array(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPayload(data) {
|
||||||
|
if (!data || data.length === 0) return '<空>';
|
||||||
|
|
||||||
|
const bytes = toBytes(data);
|
||||||
|
|
||||||
|
// 尝试作为文本显示
|
||||||
|
try {
|
||||||
|
const text = new TextDecoder().decode(bytes);
|
||||||
|
if (/^[\x20-\x7E\s]+$/.test(text)) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
// 作为十六进制显示
|
||||||
|
const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
|
||||||
|
return `HEX: ${hex}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
const list = document.getElementById('msgList');
|
||||||
|
document.getElementById('count').textContent = `共 ${allMessages.length} 条消息`;
|
||||||
|
|
||||||
|
if (allMessages.length === 0) {
|
||||||
|
list.innerHTML = '<div class="empty">暂无消息,等待数据...</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
list.innerHTML = allMessages.map(msg => {
|
||||||
|
const isJson = msg.topic.includes('/json/');
|
||||||
|
let itemClass = 'msg-item';
|
||||||
|
let badge, badgeClass;
|
||||||
|
|
||||||
|
// 检查是否有解密结果
|
||||||
|
if (isJson) {
|
||||||
|
itemClass += ' json';
|
||||||
|
badge = 'JSON';
|
||||||
|
badgeClass = 'badge-json';
|
||||||
|
} else if (msg.decrypted && msg.decrypted.payload && msg.decrypted.payload.length > 0) {
|
||||||
|
itemClass += ' decrypted';
|
||||||
|
badge = '已解密';
|
||||||
|
badgeClass = 'badge-dec';
|
||||||
|
} else if (msg.decrypted) {
|
||||||
|
itemClass += ' encrypted';
|
||||||
|
badge = msg.decrypted.channel_id ? '加密' : '失败';
|
||||||
|
badgeClass = 'badge-err';
|
||||||
|
} else {
|
||||||
|
itemClass += ' encrypted';
|
||||||
|
badge = '原始';
|
||||||
|
badgeClass = 'badge-enc';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建元数据行
|
||||||
|
let metaHtml = '';
|
||||||
|
if (msg.decrypted) {
|
||||||
|
const d = msg.decrypted;
|
||||||
|
metaHtml = `
|
||||||
|
<div class="msg-meta">
|
||||||
|
${d.channel_id ? `<span><span class="label">频道:</span> ${esc(d.channel_id)}</span>` : ''}
|
||||||
|
${d.gateway_id ? `<span><span class="label">网关:</span> ${esc(d.gateway_id)}</span>` : ''}
|
||||||
|
${d.packet_id ? `<span><span class="label">ID:</span> ${d.packet_id}</span>` : ''}
|
||||||
|
${d.from ? `<span><span class="label">From:</span> 0x${d.from.toString(16)}</span>` : ''}
|
||||||
|
${d.port_num ? `<span class="port-badge">${getPortName(d.port_num)}</span>` : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建 payload
|
||||||
|
let payloadHtml = '';
|
||||||
|
if (isJson) {
|
||||||
|
// JSON 消息直接显示
|
||||||
|
try {
|
||||||
|
const raw = atob(msg.payload);
|
||||||
|
payloadHtml = `<div class="msg-payload">${esc(raw)}</div>`;
|
||||||
|
} catch {
|
||||||
|
payloadHtml = `<div class="msg-payload">${esc(msg.payload)}</div>`;
|
||||||
|
}
|
||||||
|
} else if (msg.decrypted && msg.decrypted.payload && msg.decrypted.payload.length > 0) {
|
||||||
|
// 解密成功,显示解密后的数据
|
||||||
|
const payloadText = formatPayload(msg.decrypted.payload);
|
||||||
|
payloadHtml = `<div class="msg-payload decrypted">${esc(payloadText)}</div>`;
|
||||||
|
} else if (msg.decrypted && msg.decrypted.gateway_id) {
|
||||||
|
// 解密失败,显示错误信息和原始 base64
|
||||||
|
const errMsg = esc(msg.decrypted.gateway_id);
|
||||||
|
payloadHtml = `<div class="msg-payload hex">
|
||||||
|
<span style="color:#ff4d4f;font-size:11px;">解密失败: ${errMsg}</span>
|
||||||
|
<br>原始: ${esc(msg.payload)}
|
||||||
|
</div>`;
|
||||||
|
} else {
|
||||||
|
// 没有解密,显示原始
|
||||||
|
try {
|
||||||
|
const raw = atob(msg.payload);
|
||||||
|
const hex = Array.from(raw).map(b => b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
|
||||||
|
payloadHtml = `<div class="msg-payload hex">${esc(hex)}</div>`;
|
||||||
|
} catch {
|
||||||
|
payloadHtml = `<div class="msg-payload">${esc(msg.payload)}</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<div class="${itemClass}">
|
||||||
|
<div class="msg-header">
|
||||||
|
<span class="msg-time">${formatTime(msg.time)}</span>
|
||||||
|
<span class="msg-topic">${esc(msg.topic)}</span>
|
||||||
|
<span class="badge ${badgeClass}">${badge}</span>
|
||||||
|
</div>
|
||||||
|
${metaHtml}
|
||||||
|
${payloadHtml}
|
||||||
|
</div>`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
let allMessages = [];
|
||||||
|
|
||||||
|
function fetchMessages() {
|
||||||
|
fetch('/admin/meshtastic/api/messages')
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(res => {
|
||||||
|
if (res.code === 0) {
|
||||||
|
allMessages = res.data;
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(err => console.error('fetch error:', err));
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchMessages();
|
||||||
|
setInterval(fetchMessages, 3000);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+492
-23
@@ -2,14 +2,200 @@ package stats
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
mqtt "github.com/mochi-mqtt/server/v2"
|
mqtt "github.com/mochi-mqtt/server/v2"
|
||||||
"github.com/mochi-mqtt/server/v2/packets"
|
"github.com/mochi-mqtt/server/v2/packets"
|
||||||
|
"google.golang.org/protobuf/encoding/protowire"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Meshtastic Protobuf 手动解析 (简化版)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// MeshPacket 简化版,只包含解密所需字段
|
||||||
|
type MeshPacket struct {
|
||||||
|
Id uint64
|
||||||
|
From uint32
|
||||||
|
WhichPayloadVariant int // 10=decoded, 11=encrypted
|
||||||
|
Encrypted []byte
|
||||||
|
DecryptedPayload []byte // field 7: decoded.payload
|
||||||
|
PkiEncrypted bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceEnvelope 简化版
|
||||||
|
type ServiceEnvelope struct {
|
||||||
|
ChannelId string
|
||||||
|
GatewayId string
|
||||||
|
Packet *MeshPacket
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseServiceEnvelope 解析 ServiceEnvelope 二进制 protobuf
|
||||||
|
func ParseServiceEnvelope(data []byte) (*ServiceEnvelope, error) {
|
||||||
|
env := &ServiceEnvelope{}
|
||||||
|
|
||||||
|
pos := 0
|
||||||
|
for pos < len(data) {
|
||||||
|
fieldNum, wireType, n := protowire.ConsumeTag(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid wire format at pos %d", pos)
|
||||||
|
}
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case int(fieldNum) == 1 && wireType == protowire.BytesType:
|
||||||
|
msgData, n := protowire.ConsumeBytes(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid bytes at pos %d", pos)
|
||||||
|
}
|
||||||
|
pos += n
|
||||||
|
packet, err := parseMeshPacket(msgData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse packet: %w", err)
|
||||||
|
}
|
||||||
|
env.Packet = packet
|
||||||
|
|
||||||
|
case int(fieldNum) == 2 && wireType == protowire.BytesType:
|
||||||
|
val, n := protowire.ConsumeBytes(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid bytes at pos %d", pos)
|
||||||
|
}
|
||||||
|
env.ChannelId = string(val)
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 3 && wireType == protowire.BytesType:
|
||||||
|
val, n := protowire.ConsumeBytes(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid bytes at pos %d", pos)
|
||||||
|
}
|
||||||
|
env.GatewayId = string(val)
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
default:
|
||||||
|
n, ok := skipField(data[pos:], int(fieldNum), wireType)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("skip failed at pos %d", pos)
|
||||||
|
}
|
||||||
|
pos += n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return env, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseMeshPacket 解析 MeshPacket
|
||||||
|
func parseMeshPacket(data []byte) (*MeshPacket, error) {
|
||||||
|
packet := &MeshPacket{}
|
||||||
|
|
||||||
|
pos := 0
|
||||||
|
for pos < len(data) {
|
||||||
|
fieldNum, wireType, n := protowire.ConsumeTag(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid wire format at pos %d", pos)
|
||||||
|
}
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case int(fieldNum) == 1 && wireType == protowire.VarintType:
|
||||||
|
val, n := protowire.ConsumeVarint(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid varint at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.Id = val
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 3 && wireType == protowire.VarintType:
|
||||||
|
val, n := protowire.ConsumeVarint(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid varint at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.From = uint32(val)
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 8 && wireType == protowire.VarintType:
|
||||||
|
val, n := protowire.ConsumeVarint(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid varint at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.WhichPayloadVariant = int(val)
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 11 && wireType == protowire.BytesType:
|
||||||
|
// encrypted 字段 (variant 11)
|
||||||
|
val, n := protowire.ConsumeBytes(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid bytes at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.Encrypted = val
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 7 && wireType == protowire.BytesType:
|
||||||
|
// decoded.payload 字段 (variant 10) - 已经是解密的数据
|
||||||
|
val, n := protowire.ConsumeBytes(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid bytes at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.DecryptedPayload = val
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
case int(fieldNum) == 15 && wireType == protowire.VarintType:
|
||||||
|
val, n := protowire.ConsumeVarint(data[pos:])
|
||||||
|
if n < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid varint at pos %d", pos)
|
||||||
|
}
|
||||||
|
packet.PkiEncrypted = val != 0
|
||||||
|
pos += n
|
||||||
|
|
||||||
|
default:
|
||||||
|
skipped, ok := skipField(data[pos:], int(fieldNum), wireType)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("skip failed at pos %d", pos)
|
||||||
|
}
|
||||||
|
pos += skipped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return packet, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// skipField 跳过未知 protobuf 字段
|
||||||
|
func skipField(data []byte, fieldNum int, wireType protowire.Type) (int, bool) {
|
||||||
|
switch wireType {
|
||||||
|
case protowire.VarintType:
|
||||||
|
_, n := protowire.ConsumeVarint(data)
|
||||||
|
if n < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return n, true
|
||||||
|
case protowire.Fixed32Type:
|
||||||
|
if len(data) < 4 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return 4, true
|
||||||
|
case protowire.Fixed64Type:
|
||||||
|
if len(data) < 8 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return 8, true
|
||||||
|
case protowire.BytesType:
|
||||||
|
_, n := protowire.ConsumeBytes(data)
|
||||||
|
if n < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return n, true
|
||||||
|
case protowire.StartGroupType, protowire.EndGroupType:
|
||||||
|
return 0, false
|
||||||
|
default:
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 数据结构
|
// 数据结构
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -25,31 +211,51 @@ type ClientInfo struct {
|
|||||||
|
|
||||||
// Stats 当前统计快照
|
// Stats 当前统计快照
|
||||||
type Stats struct {
|
type Stats struct {
|
||||||
Connections int64 `json:"connections"` // 当前连接数
|
Connections int64 `json:"connections"`
|
||||||
MessagesTotal int64 `json:"messages_total"` // 累计消息数(所有主题)
|
MessagesTotal int64 `json:"messages_total"`
|
||||||
MessagesMsh int64 `json:"messages_msh"` // msh/# 消息数
|
MessagesMsh int64 `json:"messages_msh"`
|
||||||
Uptime int64 `json:"uptime"` // 服务运行时长(秒)
|
Uptime int64 `json:"uptime"`
|
||||||
Clients []ClientInfo `json:"clients"` // 在线客户端列表
|
Clients []ClientInfo `json:"clients"`
|
||||||
Topics map[string]int64 `json:"topics"` // 各主题消息数
|
Topics map[string]int64 `json:"topics"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecryptedMessage 解密后的消息结构
|
||||||
|
type DecryptedMessage struct {
|
||||||
|
ChannelId string `json:"channel_id"`
|
||||||
|
GatewayId string `json:"gateway_id"`
|
||||||
|
PacketId uint64 `json:"packet_id"`
|
||||||
|
From uint32 `json:"from"`
|
||||||
|
PortNum uint32 `json:"port_num"`
|
||||||
|
Payload []byte `json:"payload"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MessageRecord 一条MQTT消息记录
|
||||||
|
type MessageRecord struct {
|
||||||
|
Topic string `json:"topic"`
|
||||||
|
Payload string `json:"payload"`
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Decrypted *DecryptedMessage `json:"decrypted,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 全局统计(atomic + mutex 无锁热点路径)
|
// 全局统计
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
var (
|
var (
|
||||||
connections atomic.Int64
|
connections atomic.Int64
|
||||||
messagesTotal atomic.Int64
|
messagesTotal atomic.Int64
|
||||||
messagesMsh atomic.Int64
|
messagesMsh atomic.Int64
|
||||||
startTime = time.Now()
|
startTime = time.Now()
|
||||||
clientsMu sync.RWMutex
|
clientsMu sync.RWMutex
|
||||||
clients = make(map[string]ClientInfo) // clientID → info
|
clients = make(map[string]ClientInfo)
|
||||||
subs = make(map[string][]string) // clientID → []filter
|
subs = make(map[string][]string)
|
||||||
topicsMu sync.RWMutex
|
topicsMu sync.RWMutex
|
||||||
topics = make(map[string]int64) // topic → count
|
topics = make(map[string]int64)
|
||||||
|
msgMu sync.RWMutex
|
||||||
|
msgBuf []MessageRecord
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetStats 返回当前统计快照(只读副本)
|
// GetStats 返回当前统计快照
|
||||||
func GetStats() Stats {
|
func GetStats() Stats {
|
||||||
clientsMu.RLock()
|
clientsMu.RLock()
|
||||||
clientList := make([]ClientInfo, 0, len(clients))
|
clientList := make([]ClientInfo, 0, len(clients))
|
||||||
@@ -76,11 +282,29 @@ func GetStats() Stats {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetClient 返回指定客户端的详细信息
|
||||||
|
func GetClient(id string) *ClientInfo {
|
||||||
|
clientsMu.RLock()
|
||||||
|
defer clientsMu.RUnlock()
|
||||||
|
info, ok := clients[id]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
info.SubsCount = len(subs[id])
|
||||||
|
return &info
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetClientSubs 返回指定客户端的订阅主题列表
|
||||||
|
func GetClientSubs(id string) []string {
|
||||||
|
clientsMu.RLock()
|
||||||
|
defer clientsMu.RUnlock()
|
||||||
|
return subs[id]
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Hook 实现
|
// Hook 实现
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// Hook 收集 MQTT 运行统计
|
|
||||||
type Hook struct {
|
type Hook struct {
|
||||||
mqtt.HookBase
|
mqtt.HookBase
|
||||||
}
|
}
|
||||||
@@ -97,7 +321,6 @@ func (h *Hook) Provides(b byte) bool {
|
|||||||
}, []byte{b})
|
}, []byte{b})
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnSessionEstablished 客户端连接成功
|
|
||||||
func (h *Hook) OnSessionEstablished(cl *mqtt.Client, pk packets.Packet) {
|
func (h *Hook) OnSessionEstablished(cl *mqtt.Client, pk packets.Packet) {
|
||||||
username := string(pk.Connect.Username)
|
username := string(pk.Connect.Username)
|
||||||
if username == "" {
|
if username == "" {
|
||||||
@@ -115,7 +338,6 @@ func (h *Hook) OnSessionEstablished(cl *mqtt.Client, pk packets.Packet) {
|
|||||||
connections.Add(1)
|
connections.Add(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnDisconnect 客户端断开
|
|
||||||
func (h *Hook) OnDisconnect(cl *mqtt.Client, err error, expire bool) {
|
func (h *Hook) OnDisconnect(cl *mqtt.Client, err error, expire bool) {
|
||||||
clientsMu.Lock()
|
clientsMu.Lock()
|
||||||
delete(clients, cl.ID)
|
delete(clients, cl.ID)
|
||||||
@@ -124,11 +346,11 @@ func (h *Hook) OnDisconnect(cl *mqtt.Client, err error, expire bool) {
|
|||||||
connections.Add(-1)
|
connections.Add(-1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnPublish 收到发布消息
|
|
||||||
func (h *Hook) OnPublish(cl *mqtt.Client, pk packets.Packet) (packets.Packet, error) {
|
func (h *Hook) OnPublish(cl *mqtt.Client, pk packets.Packet) (packets.Packet, error) {
|
||||||
messagesTotal.Add(1)
|
messagesTotal.Add(1)
|
||||||
if len(pk.TopicName) >= 4 && pk.TopicName[:4] == "msh/" {
|
if len(pk.TopicName) >= 4 && pk.TopicName[:4] == "msh/" {
|
||||||
messagesMsh.Add(1)
|
messagesMsh.Add(1)
|
||||||
|
addMessage(pk.TopicName, pk.Payload)
|
||||||
}
|
}
|
||||||
topicsMu.Lock()
|
topicsMu.Lock()
|
||||||
topics[pk.TopicName]++
|
topics[pk.TopicName]++
|
||||||
@@ -136,7 +358,6 @@ func (h *Hook) OnPublish(cl *mqtt.Client, pk packets.Packet) (packets.Packet, er
|
|||||||
return pk, nil
|
return pk, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnSubscribe 客户端订阅
|
|
||||||
func (h *Hook) OnSubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
|
func (h *Hook) OnSubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
|
||||||
clientsMu.Lock()
|
clientsMu.Lock()
|
||||||
for _, f := range pk.Filters {
|
for _, f := range pk.Filters {
|
||||||
@@ -146,7 +367,6 @@ func (h *Hook) OnSubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
|
|||||||
return pk
|
return pk
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnUnsubscribe 客户端取消订阅
|
|
||||||
func (h *Hook) OnUnsubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
|
func (h *Hook) OnUnsubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet {
|
||||||
clientsMu.Lock()
|
clientsMu.Lock()
|
||||||
for _, f := range pk.Filters {
|
for _, f := range pk.Filters {
|
||||||
@@ -163,3 +383,252 @@ func (h *Hook) OnUnsubscribe(cl *mqtt.Client, pk packets.Packet) packets.Packet
|
|||||||
}
|
}
|
||||||
|
|
||||||
var _ mqtt.Hook = (*Hook)(nil)
|
var _ mqtt.Hook = (*Hook)(nil)
|
||||||
|
|
||||||
|
func addMessage(topic string, payload []byte) {
|
||||||
|
rec := MessageRecord{
|
||||||
|
Topic: topic,
|
||||||
|
Payload: base64.StdEncoding.EncodeToString(payload),
|
||||||
|
Time: time.Now(),
|
||||||
|
}
|
||||||
|
msgMu.Lock()
|
||||||
|
defer msgMu.Unlock()
|
||||||
|
msgBuf = append(msgBuf, rec)
|
||||||
|
if len(msgBuf) > 200 {
|
||||||
|
msgBuf = msgBuf[len(msgBuf)-200:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetMessages() []MessageRecord {
|
||||||
|
msgMu.RLock()
|
||||||
|
defer msgMu.RUnlock()
|
||||||
|
out := make([]MessageRecord, len(msgBuf))
|
||||||
|
copy(out, msgBuf)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseServiceEnvelopeDebug 解析但不解密(用于调试)
|
||||||
|
func ParseServiceEnvelopeDebug(payloadB64 string) (*ServiceEnvelope, error) {
|
||||||
|
data, err := base64.StdEncoding.DecodeString(payloadB64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode base64: %w", err)
|
||||||
|
}
|
||||||
|
return ParseServiceEnvelope(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Meshtastic AES-CTR 解密
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// 默认 PSK (索引1 = 不变)
|
||||||
|
var DefaultPSK = []byte{0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59, 0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0x01}
|
||||||
|
|
||||||
|
// 默认 PSK 索引 (1-8)
|
||||||
|
var defaultPSKIndex byte = 1
|
||||||
|
|
||||||
|
// Payload variant tags
|
||||||
|
const (
|
||||||
|
MeshPacket_decoded_tag = 10
|
||||||
|
MeshPacket_encrypted_tag = 11
|
||||||
|
)
|
||||||
|
|
||||||
|
// ExpandPSK 将 1 字节 PSK 索引扩展为 16 字节 AES128 密钥
|
||||||
|
func ExpandPSK(pskIndex byte) ([]byte, error) {
|
||||||
|
if pskIndex == 0 {
|
||||||
|
return nil, nil // 无加密
|
||||||
|
}
|
||||||
|
if pskIndex > 8 {
|
||||||
|
return nil, fmt.Errorf("PSK index must be 0-8, got %d", pskIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
key := make([]byte, 16)
|
||||||
|
copy(key, DefaultPSK)
|
||||||
|
|
||||||
|
// 索引1不变,索引2-8在最后一位累加
|
||||||
|
if pskIndex > 1 {
|
||||||
|
key[15] += pskIndex - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildNonce 构建 AES-CTR 用的 nonce (16字节)
|
||||||
|
// nonce 结构: packetId(8字节小端) + fromNode(4字节小端) + counter(4字节,通常为0)
|
||||||
|
func buildNonce(packetId uint64, fromNode uint32) [16]byte {
|
||||||
|
var nonce [16]byte
|
||||||
|
// packetId: 8字节,小端序
|
||||||
|
nonce[0] = byte(packetId)
|
||||||
|
nonce[1] = byte(packetId >> 8)
|
||||||
|
nonce[2] = byte(packetId >> 16)
|
||||||
|
nonce[3] = byte(packetId >> 24)
|
||||||
|
nonce[4] = byte(packetId >> 32)
|
||||||
|
nonce[5] = byte(packetId >> 40)
|
||||||
|
nonce[6] = byte(packetId >> 48)
|
||||||
|
nonce[7] = byte(packetId >> 56)
|
||||||
|
// fromNode: 4字节,小端序
|
||||||
|
nonce[8] = byte(fromNode)
|
||||||
|
nonce[9] = byte(fromNode >> 8)
|
||||||
|
nonce[10] = byte(fromNode >> 16)
|
||||||
|
nonce[11] = byte(fromNode >> 24)
|
||||||
|
// counter: 4字节,默认为0 (nonce[12-15] 已经是0)
|
||||||
|
return nonce
|
||||||
|
}
|
||||||
|
|
||||||
|
// decryptAESCtr 使用 AES-CTR 解密
|
||||||
|
func decryptAESCtr(key []byte, nonce [16]byte, ciphertext []byte) ([]byte, error) {
|
||||||
|
if len(key) != 16 {
|
||||||
|
return nil, fmt.Errorf("key must be 16 bytes, got %d", len(key))
|
||||||
|
}
|
||||||
|
if len(ciphertext) == 0 {
|
||||||
|
return nil, fmt.Errorf("ciphertext is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
stream := cipher.NewCTR(block, nonce[:])
|
||||||
|
plaintext := make([]byte, len(ciphertext))
|
||||||
|
stream.XORKeyStream(plaintext, ciphertext)
|
||||||
|
|
||||||
|
return plaintext, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecryptMeshPacket 解密 MeshPacket
|
||||||
|
func DecryptMeshPacket(psk []byte, packetId uint64, fromNode uint32, encrypted []byte) ([]byte, error) {
|
||||||
|
if psk == nil {
|
||||||
|
return nil, fmt.Errorf("no PSK configured")
|
||||||
|
}
|
||||||
|
if len(encrypted) == 0 {
|
||||||
|
return nil, fmt.Errorf("encrypted payload is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
nonce := buildNonce(packetId, fromNode)
|
||||||
|
return decryptAESCtr(psk, nonce, encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDefaultPSKIndex 设置默认 PSK 索引
|
||||||
|
func SetDefaultPSKIndex(index byte) {
|
||||||
|
defaultPSKIndex = index
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultPSK 返回当前 PSK 的 16 字节密钥
|
||||||
|
func GetDefaultPSK() []byte {
|
||||||
|
key, _ := ExpandPSK(defaultPSKIndex)
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultPSKIndex 返回当前 PSK 索引
|
||||||
|
func GetDefaultPSKIndex() byte {
|
||||||
|
return defaultPSKIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
// TryDecryptServiceEnvelope 尝试解密 ServiceEnvelope
|
||||||
|
func TryDecryptServiceEnvelope(data []byte, pskIndex byte) (*DecryptedMessage, error) {
|
||||||
|
psk, err := ExpandPSK(pskIndex)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
env, err := ParseServiceEnvelope(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if env.Packet == nil {
|
||||||
|
return nil, fmt.Errorf("ServiceEnvelope has no packet")
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := &DecryptedMessage{
|
||||||
|
ChannelId: env.ChannelId,
|
||||||
|
GatewayId: env.GatewayId,
|
||||||
|
PacketId: env.Packet.Id,
|
||||||
|
From: env.Packet.From,
|
||||||
|
}
|
||||||
|
|
||||||
|
// variant 10: 已经解密的数据 (decoded.payload)
|
||||||
|
if env.Packet.WhichPayloadVariant == MeshPacket_decoded_tag {
|
||||||
|
if len(env.Packet.DecryptedPayload) > 0 {
|
||||||
|
msg.Payload = env.Packet.DecryptedPayload
|
||||||
|
// portnum 是解密数据的第一个字节
|
||||||
|
msg.PortNum = uint32(env.Packet.DecryptedPayload[0])
|
||||||
|
}
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// variant 11: 加密数据,需要解密
|
||||||
|
if env.Packet.WhichPayloadVariant == MeshPacket_encrypted_tag && !env.Packet.PkiEncrypted {
|
||||||
|
plaintext, err := DecryptMeshPacket(psk, env.Packet.Id, env.Packet.From, env.Packet.Encrypted)
|
||||||
|
if err != nil {
|
||||||
|
return msg, fmt.Errorf("decryption failed: %w", err)
|
||||||
|
}
|
||||||
|
msg.Payload = plaintext
|
||||||
|
|
||||||
|
// 解析 portnum (第一个字节)
|
||||||
|
if len(plaintext) > 0 {
|
||||||
|
msg.PortNum = uint32(plaintext[0])
|
||||||
|
}
|
||||||
|
} else if env.Packet.WhichPayloadVariant == MeshPacket_encrypted_tag && env.Packet.PkiEncrypted {
|
||||||
|
return msg, fmt.Errorf("PKI encrypted packet (not supported)")
|
||||||
|
} else {
|
||||||
|
return msg, fmt.Errorf("unknown packet variant: %d", env.Packet.WhichPayloadVariant)
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TryDecryptMessage 尝试解密消息
|
||||||
|
func TryDecryptMessage(payloadB64 string, pskIndex byte) (*DecryptedMessage, error) {
|
||||||
|
data, err := base64.StdEncoding.DecodeString(payloadB64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode base64: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return TryDecryptServiceEnvelope(data, pskIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PortNumName 返回 PortNum 对应的名称
|
||||||
|
func PortNumName(portNum uint32) string {
|
||||||
|
names := map[uint32]string{
|
||||||
|
0: "Reserved",
|
||||||
|
1: "TEXT_MESSAGE_APP",
|
||||||
|
2: "REMOTE_HARDWARE_APP",
|
||||||
|
3: "POSITION_APP",
|
||||||
|
4: "NODEINFO_APP",
|
||||||
|
5: "ROUTING_APP",
|
||||||
|
6: "ADMIN_APP",
|
||||||
|
7: "TEXT_MESSAGE_APP2",
|
||||||
|
8: "WAYPOINT_APP",
|
||||||
|
9: "WIFI_APP",
|
||||||
|
10: "MXT_AI_APP",
|
||||||
|
11: "RANGE_TEST_APP",
|
||||||
|
12: "DETECTION_SENSOR_APP",
|
||||||
|
13: "REPLY_APP",
|
||||||
|
14: "IP_TUNNEL_APP",
|
||||||
|
15: "SERIAL_APP",
|
||||||
|
16: "STORE_FORWARD_APP",
|
||||||
|
17: "TELEMETRY_APP",
|
||||||
|
18: "ZPS_APP",
|
||||||
|
19: "SIMULATOR_APP",
|
||||||
|
20: "TRACEROUTE_APP",
|
||||||
|
21: "NEIGHBORINFO_APP",
|
||||||
|
22: "AUDIO_APP",
|
||||||
|
23: "DUPLICATE_MESSAGES_APP",
|
||||||
|
24: "ACKNOWLEDGEMENT_APP",
|
||||||
|
25: "CONFIG_APP",
|
||||||
|
26: "IPLY_CONFIG_APP",
|
||||||
|
27: "MAP_REPORT_APP",
|
||||||
|
28: "PaxCounter_APP",
|
||||||
|
32: "PRIVATE_APP",
|
||||||
|
256: "ATAK_PLUGIN",
|
||||||
|
257: "HALP",
|
||||||
|
258: "RPC_APP",
|
||||||
|
259: "XMPP_APP",
|
||||||
|
260: "STREAM_APP",
|
||||||
|
261: "TUNNEL_APP",
|
||||||
|
}
|
||||||
|
if name, ok := names[portNum]; ok {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("Unknown(%d)", portNum)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user