From 5f6ea83e5ba0fedbf1852de9fe7e1da901fca810 Mon Sep 17 00:00:00 2001 From: Sakurasan <26715255+Sakurasan@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:10:14 +0800 Subject: [PATCH] =?UTF-8?q?=E7=9C=8B=E6=9D=BF=E5=8D=95=E8=AE=BE=E5=A4=877?= =?UTF-8?q?=E6=97=A5=E5=8E=86=E5=8F=B2:=20/api/device=E7=AB=AF=E7=82=B9=20?= =?UTF-8?q?+=20=E7=82=B9=E5=87=BB=E8=AE=BE=E5=A4=87=E8=A1=8C=E5=B1=95?= =?UTF-8?q?=E5=BC=80=E8=AF=A6=E6=83=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + server.go | 56 ++++++++++++++++++ server_test.go | 91 ++++++++++++++++++++++++++++++ web/dashboard.html | 138 ++++++++++++++++++++++++++++++++++++++++----- 4 files changed, 272 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index db1c3a2..4d866f2 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ - 站点切换栏(每个上报的 site 一个按钮,显示在线/总数) - 统计卡片:在线/离线/总数/事件数 - 设备表:状态、MAC、IP、首次/最近上线/下线、在线次数、累计在线 +- **点击设备行 → 展开该设备 7 日上下线历史**(上线/下线次数、累计在线、完整事件流) - 事件流:上下线事件,最新在前 - 每 5 秒自动刷新 @@ -160,6 +161,7 @@ WiFi 连接 → 登录路由器抓原始 DHCP 页面 → POST `/api/raw` → 深 | `POST /api/raw` | ESP8266 原始页面上报(Header X-Token/X-Site,body=原始HTML),服务器端解析判定 | | `GET /api/sites` | 站点列表(在线数/设备数/最近上报) | | `GET /api/site?site=X` | 单站点详情(设备+事件) | +| `GET /api/device?site=X&mac=Y` | 单设备 7 日历史(该设备保留期内全部上下线事件) | **client 模式**(本地): | 端点 | 说明 | diff --git a/server.go b/server.go index f7de319..0a6683b 100644 --- a/server.go +++ b/server.go @@ -83,6 +83,7 @@ func runServer(cfg ServerConfig) { mux.HandleFunc("/api/raw", s.handleRaw) mux.HandleFunc("/api/sites", s.handleSites) mux.HandleFunc("/api/site", s.handleSite) + mux.HandleFunc("/api/device", s.handleDevice) srv := &http.Server{Addr: cfg.Addr, Handler: mux} fmt.Printf("[%s] 看板服务器启动: http://%s | 数据目录 %s | 保留 %d 天\n", time.Now().Format("2006-01-02 15:04:05"), cfg.Addr, cfg.DataDir, cfg.RetainDays) @@ -511,6 +512,61 @@ func (s *Server) handleSite(w http.ResponseWriter, r *http.Request) { }) } +// handleDevice 单设备详情: 返回该设备在保留期内(retainDays)的全部上下线事件 +func (s *Server) handleDevice(w http.ResponseWriter, r *http.Request) { + if !s.authOK(r) { + http.Error(w, "403", http.StatusForbidden) + return + } + name := r.URL.Query().Get("site") + mac := r.URL.Query().Get("mac") + if name == "" || mac == "" { + http.Error(w, "缺少 site 或 mac 参数", http.StatusBadRequest) + return + } + s.mu.RLock() + sd, ok := s.sites[name] + s.mu.RUnlock() + if !ok { + http.Error(w, "站点不存在", http.StatusNotFound) + return + } + + cutoff := time.Now().Add(-time.Duration(s.retainDays) * 24 * time.Hour) + macKey := strings.ToUpper(mac) + + sd.mu.RLock() + dev := sd.devices[macKey] + evs := make([]Event, 0, len(sd.events)) + for _, e := range sd.events { + if strings.ToUpper(e.MAC) != macKey || e.Timestamp.Before(cutoff) { + continue + } + evs = append(evs, e) + } + last := sd.lastSeen + sd.mu.RUnlock() + + if dev == nil { + http.Error(w, "设备不存在", http.StatusNotFound) + return + } + + // 事件最新在前 + for i, j := 0, len(evs)-1; i < j; i, j = i+1, j-1 { + evs[i], evs[j] = evs[j], evs[i] + } + + w.Header().Set("Content-Type", "application/json; charset=utf-8") + json.NewEncoder(w).Encode(map[string]interface{}{ + "site": name, + "device": dev, + "events": evs, + "last_seen": last.Format(time.RFC3339), + "retain_days": s.retainDays, + }) +} + // saveSite 持久化单站点数据 func (s *Server) saveSite(sd *SiteData) { dir := filepath.Join(s.dataDir, "sites", sanitize(sd.name)) diff --git a/server_test.go b/server_test.go index a772bed..253a7a3 100644 --- a/server_test.go +++ b/server_test.go @@ -98,6 +98,97 @@ func TestReportSnapshotMerge(t *testing.T) { } } +// 测试: 单设备7日历史查询 /api/device +func TestDeviceHistory(t *testing.T) { + s := &Server{ + dataDir: t.TempDir(), + token: "secret", + retainDays: 7, + sites: make(map[string]*SiteData), + } + sd := &SiteData{name: "s1", devices: make(map[string]*Device)} + s.mu.Lock() + s.sites["s1"] = sd + s.mu.Unlock() + + now := time.Now() + dev := &Device{ + MAC: "AA:BB:CC:DD:EE:01", + Name: "Phone", + LastIP: "1.1.1.1", + Status: evOnline, + FirstSeen: now.Add(-3 * 24 * time.Hour), + OnlineCount: 2, + TotalOnline: 7200, + } + sd.mu.Lock() + sd.devices[dev.MAC] = dev + // 该设备的上下线事件(2天内) + sd.events = append(sd.events, + Event{Timestamp: now.Add(-48 * time.Hour), Event: evOnline, MAC: dev.MAC, IP: "1.1.1.1", Name: "Phone"}, + Event{Timestamp: now.Add(-47 * time.Hour), Event: evOffline, MAC: dev.MAC, IP: "1.1.1.1", Name: "Phone"}, + Event{Timestamp: now.Add(-24 * time.Hour), Event: evOnline, MAC: dev.MAC, IP: "1.1.1.1", Name: "Phone"}, + // 别的设备事件,不应返回 + Event{Timestamp: now.Add(-1 * time.Hour), Event: evOnline, MAC: "FF:FF:FF:FF:FF:FF", IP: "1.1.1.2", Name: "Other"}, + // 超过7天的事件,不应返回 + Event{Timestamp: now.Add(-8 * 24 * time.Hour), Event: evOnline, MAC: dev.MAC, IP: "1.1.1.1", Name: "Phone"}, + ) + sd.mu.Unlock() + + // 无token拒绝 + r := httptest.NewRequest("GET", "/api/device?site=s1&mac="+dev.MAC, nil) + w := httptest.NewRecorder() + s.handleDevice(w, r) + if w.Code != http.StatusForbidden { + t.Fatalf("无token应403, got %d", w.Code) + } + + // 正确token + r = httptest.NewRequest("GET", "/api/device?site=s1&mac="+dev.MAC+"&token=secret", nil) + w = httptest.NewRecorder() + s.handleDevice(w, r) + if w.Code != http.StatusOK { + t.Fatalf("应200, got %d: %s", w.Code, w.Body.String()) + } + var resp struct { + Device *Device `json:"device"` + Events []Event `json:"events"` + Retain int `json:"retain_days"` + } + if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { + t.Fatalf("响应非JSON: %v", err) + } + if resp.Device == nil || resp.Device.MAC != dev.MAC { + t.Fatalf("device 应返回, got %+v", resp.Device) + } + if len(resp.Events) != 3 { + t.Fatalf("应返回该设备3条事件(不含别设备/超期), got %d: %+v", len(resp.Events), resp.Events) + } + // 最新在前 + if resp.Events[0].Timestamp.Before(resp.Events[1].Timestamp) { + t.Fatal("事件应按时间倒序(最新在前)") + } + if resp.Retain != 7 { + t.Fatalf("retain_days 应7, got %d", resp.Retain) + } + + // 不存在设备 + r = httptest.NewRequest("GET", "/api/device?site=s1&mac=00:00:00:00:00:00&token=secret", nil) + w = httptest.NewRecorder() + s.handleDevice(w, r) + if w.Code != http.StatusNotFound { + t.Fatalf("不存在设备应404, got %d", w.Code) + } + + // 缺参 + r = httptest.NewRequest("GET", "/api/device?site=s1&token=secret", nil) + w = httptest.NewRecorder() + s.handleDevice(w, r) + if w.Code != http.StatusBadRequest { + t.Fatalf("缺mac应400, got %d", w.Code) + } +} + // 测试: 多站点隔离 func TestMultiSite(t *testing.T) { s := &Server{ diff --git a/web/dashboard.html b/web/dashboard.html index 45d3112..2a36b02 100644 --- a/web/dashboard.html +++ b/web/dashboard.html @@ -53,6 +53,21 @@ .rpt .detail { color: var(--muted); font-size: 12px; flex-basis: 100%; padding-left: 16px; } .badge.ok { background: rgba(34,197,94,.15); color: var(--green); } .badge.fail { background: rgba(239,68,68,.15); color: var(--red); } + /* 设备行可点击 → 单设备7日详情 */ + tbody tr.clickable { cursor: pointer; } + tbody tr.selected td { background: rgba(59,130,246,.12); } + .devdetail { display: none; } + .devdetail.show { display: block; } + .devdetail .head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; } + .devdetail .head .mac { font-size: 14px; } + .devdetail .head .name { font-size: 16px; font-weight: 700; } + .devdetail .close { margin-left: auto; background: none; border: 1px solid var(--border); color: var(--muted); border-radius: 8px; padding: 4px 12px; cursor: pointer; font-size: 13px; } + .devdetail .close:hover { color: var(--red); border-color: var(--red); } + .dstats { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; margin-bottom: 14px; } + .dstat { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; } + .dstat .num { font-size: 20px; font-weight: 700; } + .dstat .lbl { color: var(--muted); font-size: 12px; margin-top: 2px; } + .dstat .num.up { color: var(--green); } .dstat .num.down { color: var(--red); } .footer { color: var(--muted); font-size: 12px; text-align: center; padding: 10px 0 30px; } .scroll { max-height: 460px; overflow-y: auto; } .empty { color: var(--muted); padding: 20px 0; text-align: center; } @@ -87,6 +102,12 @@ .evt { flex-wrap: wrap; gap: 4px 8px; padding: 8px 0; font-size: 12.5px; } .evt .time { width: 100%; font-size: 12px; } .evt .detail { flex-basis: 100%; padding-left: 16px; } + /* 单设备详情在移动端紧凑 */ + .devdetail .head { gap: 6px; } + .devdetail .head .name { font-size: 15px; } + .dstats { grid-template-columns: repeat(2, 1fr); gap: 6px; } + .dstat { padding: 8px 10px; } + .dstat .num { font-size: 17px; } } @@ -107,7 +128,7 @@
-

设备列表

+

设备列表 (点击行查看该设备 7 日上下线记录)

@@ -117,6 +138,22 @@
状态设备名MAC 地址IP 地址
+
+
+ + + + +
+
+
-
7日上线次数
+
-
7日下线次数
+
-
累计在线
+
-
最近IP
+
+
+
+

最近事件

@@ -146,6 +183,8 @@ const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'< let currentSite = null; let siteMap = {}; +let selectedMac = null; // 当前查看详情的设备 MAC +let currentDevices = []; // 当前站点设备列表(供详情重渲染) // 从 URL 读取 token(?token=xxx),所有 API 请求带上 const urlParams = new URLSearchParams(window.location.search); @@ -168,7 +207,13 @@ async function loadSites() { const btn = document.createElement('button'); btn.className = 'sitebtn' + (s.site === currentSite ? ' active' : ''); btn.innerHTML = `${esc(s.site)} ${s.online_count}/${s.device_count}`; - btn.onclick = () => { currentSite = s.site; loadSite(); loadSites(); }; + btn.onclick = () => { + if (s.site === currentSite) return; + currentSite = s.site; + selectedMac = null; + $('devdetail').classList.remove('show'); + loadSite(); loadSites(); + }; bar.appendChild(btn); }); if (!currentSite && data.sites && data.sites.length) { @@ -189,7 +234,7 @@ async function loadSite() { } try { const data = await fetch(api('/api/site?site=' + encodeURIComponent(currentSite) + '&limit=100')).then(r => r.json()); - $('dev-title').textContent = `设备列表 · ${esc(currentSite)}`; + $('dev-title').innerHTML = `设备列表 · ${esc(currentSite)} (点击行查看该设备 7 日上下线记录)`; let online = 0, offline = 0; (data.devices || []).forEach(d => { if (d.status === 'online') online++; else offline++; }); @@ -199,18 +244,7 @@ async function loadSite() { $('st-total').textContent = (data.devices || []).length; $('st-events').textContent = (data.events || []).length; - $('devices').innerHTML = (data.devices || []).map(d => ` - - ${d.status === 'online' ? '在线' : '离线'} - ${esc(d.name || '-')} - ${esc(d.mac)} - ${esc(d.last_ip || '-')} - ${fmtTime(d.first_seen)} - ${fmtTime(d.last_online)} - ${fmtTime(d.last_offline)} - ${d.online_count ?? 0} - ${fmtDur(d.total_online_seconds)} - `).join('') || '暂无设备'; + renderDeviceRows(data.devices || []); $('events').innerHTML = (data.events || []).map(e => { const up = e.event === 'online'; @@ -236,11 +270,85 @@ async function loadSite() { }).join('') || '
暂无推送记录
'; $('footer').textContent = `当前站点: ${currentSite} · 最近上报 ${fmtTime(data.last_seen)} · 页面自动刷新 · ${new Date().toLocaleString()}`; + + // 若详情面板开着,随轮询一起刷新 + if (selectedMac) loadDeviceDetail(); } catch (e) { $('footer').textContent = '加载站点失败: ' + e.message; } } +// 渲染设备行(可点击查看详情) +function renderDeviceRows(devices) { + currentDevices = devices; + $('devices').innerHTML = devices.map(d => ` + + ${d.status === 'online' ? '在线' : '离线'} + ${esc(d.name || '-')} + ${esc(d.mac)} + ${esc(d.last_ip || '-')} + ${fmtTime(d.first_seen)} + ${fmtTime(d.last_online)} + ${fmtTime(d.last_offline)} + ${d.online_count ?? 0} + ${fmtDur(d.total_online_seconds)} + `).join('') || '暂无设备'; + + // 点击设备行 → 查看该设备7日历史 + $('devices').querySelectorAll('tr.clickable').forEach(tr => { + tr.onclick = () => { + selectedMac = tr.dataset.mac; + renderDeviceRows(devices); + loadDeviceDetail(); + }; + }); +} + +// 关闭单设备详情 +function closeDeviceDetail() { + selectedMac = null; + $('devdetail').classList.remove('show'); + renderDeviceRows(currentDevices); +} + +// 加载并展示单设备 7 日上下线历史 +async function loadDeviceDetail() { + if (!currentSite || !selectedMac) return; + const panel = $('devdetail'); + panel.classList.add('show'); + $('dd-events').innerHTML = '
加载中…
'; + $('dd-up').textContent = $('dd-down').textContent = $('dd-dur').textContent = '-'; + try { + const data = await fetch(api(`/api/device?site=${encodeURIComponent(currentSite)}&mac=${encodeURIComponent(selectedMac)}`)).then(r => r.json()); + const d = data.device || {}; + $('dd-name').textContent = d.name || '(未命名)'; + $('dd-mac').textContent = d.mac; + $('dd-status').innerHTML = `${d.status === 'online' ? '在线' : '离线'}`; + $('dd-ip').textContent = d.last_ip || '-'; + $('dd-dur').textContent = fmtDur(d.total_online_seconds); + + const evs = data.events || []; + $('dd-up').textContent = evs.filter(e => e.event === 'online').length; + $('dd-down').textContent = evs.filter(e => e.event === 'offline').length; + + $('dd-events').innerHTML = evs.map(e => { + const up = e.event === 'online'; + return `
+ + ${fmtTime(e.timestamp)} + ${esc(e.name || '-')} + ${esc(e.ip || '')} + ${esc(e.detail || '')} +
`; + }).join('') || '
该设备 7 日内暂无上下线事件
'; + } catch (e) { + $('dd-events').innerHTML = '
加载失败: ' + esc(e.message) + '
'; + } +} + +// 关闭按钮 +$('dd-close').onclick = closeDeviceDetail; + loadSites(); loadSite(); setInterval(() => { loadSites(); loadSite(); }, 5000);