This commit is contained in:
2026-05-15 22:03:46 +08:00
parent e6a7565745
commit e047eacfdc
6 changed files with 1239 additions and 272 deletions
+233
View File
@@ -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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// 每 3 秒刷新
fetchStats();
setInterval(fetchStats, 3000);
</script>
</body>
</html>
+123
View File
@@ -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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
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
View File
@@ -36,9 +36,19 @@ func New(cfg *config.AdminConfig) *Server {
{
admin.GET("/api/stats", handleStats)
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
if addr == "" {
@@ -90,23 +100,76 @@ func (s *Server) Enabled() bool { return s.enabled }
// serveIndex 返回管理页面
func serveIndex(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, indexHTML)
c.String(http.StatusOK, homeHTML)
}
// serveHome 主页(meshmap 占位)
func serveHome(c *gin.Context) {
// serveAdmin MQTT 管理页面
func serveAdmin(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, `<!DOCTYPE html>
<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">
<div style="text-align:center">
<h1 style="font-size:48px;color:#1677ff;margin-bottom:8px">meshmap</h1>
<p style="color:#888;margin-bottom:24px">Mesh Network Map · 网格拓扑可视化</p>
<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>
</html>`)
c.String(http.StatusOK, adminHTML)
}
// serveClientDetail 客户端详情页面
func serveClientDetail(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, clientDetailHTML)
}
// serveMeshtastic Meshtastic 消息查看页面
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
@@ -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 选择对应认证策略
@@ -168,4 +258,13 @@ func basicAuth(user, pass string) gin.HandlerFunc {
// ---------------------------------------------------------------------------
//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
View File
@@ -1,237 +1,11 @@
<!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; }
.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>
<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">
<div style="text-align:center">
<h1 style="font-size:48px;color:#1677ff;margin-bottom:8px">meshmap</h1>
<p style="color:#888;margin-bottom:24px">Mesh Network Map · 网格拓扑可视化</p>
<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>
<!-- 图表 -->
<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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// 每 3 秒刷新
fetchStats();
setInterval(fetchStats, 3000);
</script>
</body>
</html>
+269
View File
@@ -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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
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>