Initial LanUps implementation and native installers

This commit is contained in:
tongtong committed 2026-11-28 16:26:39 +08:00
commit 67a043c89b
66 files changed
+2870

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
package monitor
import (
"sync"
"time"
"lan-ups/internal/nut"
)
type Snapshot struct {
Source string `json:"source"`
Health string `json:"health"`
LastOK *time.Time `json:"lastOK,omitempty"`
Values map[string]string `json:"values,omitempty"`
Error string `json:"error,omitempty"`
}
type Monitor struct {
address string
name string
mu sync.RWMutex
state Snapshot
}
func New(address, name string) *Monitor {
return &Monitor{
address: address,
name: name,
state: Snapshot{Source: name + "@" + address, Health: "waiting"},
}
}
func (m *Monitor) Run(interval time.Duration) {
for {
values, err := nut.ReadUPS(m.address, m.name, 2*time.Second)
m.mu.Lock()
if err != nil {
m.state.Health, m.state.Error = "stale", err.Error()
} else {
now := time.Now()
m.state.Health, m.state.Error = "live", ""
m.state.LastOK, m.state.Values = &now, values
}
m.mu.Unlock()
time.Sleep(interval)
}
}
// Snapshot returns the current state. Its values must be treated as read-only.
func (m *Monitor) Snapshot() Snapshot {
m.mu.RLock()
defer m.mu.RUnlock()
return m.state
}
+61
View File
@@ -0,0 +1,61 @@
package nut
import (
"bufio"
"errors"
"fmt"
"io"
"net"
"strings"
"time"
)
func ReadUPS(address, name string, timeout time.Duration) (map[string]string, error) {
deadline := time.Now().Add(timeout)
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
return nil, err
}
defer conn.Close()
if err := conn.SetDeadline(deadline); err != nil {
return nil, err
}
request := "LIST VAR " + name
if _, err := fmt.Fprintln(conn, request); err != nil {
return nil, err
}
scanner := bufio.NewScanner(io.LimitReader(conn, 256*1024))
if !scanner.Scan() {
return nil, incomplete(scanner)
}
if scanner.Text() != "BEGIN "+request {
return nil, fmt.Errorf("NUT: %s", scanner.Text())
}
values := make(map[string]string)
prefix := "VAR " + name + " "
for scanner.Scan() {
line := scanner.Text()
if line == "END "+request {
if strings.TrimSpace(values["ups.status"]) == "" {
return nil, errors.New("NUT 未返回 ups.status")
}
return values, nil
}
row, ok := strings.CutPrefix(line, prefix)
key, quoted, separated := strings.Cut(row, " ")
if !ok || !separated || key == "" || len(quoted) < 2 || quoted[0] != '"' || quoted[len(quoted)-1] != '"' {
return nil, fmt.Errorf("NUT: %s", line)
}
values[key] = nutEscapes.Replace(quoted[1 : len(quoted)-1])
}
return nil, incomplete(scanner)
}
var nutEscapes = strings.NewReplacer(`\\`, `\`, `\"`, `"`)
func incomplete(scanner *bufio.Scanner) error {
if err := scanner.Err(); err != nil {
return err
}
return io.ErrUnexpectedEOF
}
+47
View File
@@ -0,0 +1,47 @@
package nut
import (
"bufio"
"fmt"
"net"
"testing"
"time"
)
func TestNUTRecoversFromStaleData(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
responses := []string{
"BEGIN LIST VAR h1000m\nVAR h1000m ups.status \"OL\"\nEND LIST VAR h1000m\n",
"ERR DATA-STALE\n",
"BEGIN LIST VAR h1000m\nVAR h1000m ups.status \"OB LB\"\nEND LIST VAR h1000m\n",
}
go func() {
for _, response := range responses {
conn, err := listener.Accept()
if err != nil {
return
}
conn.SetDeadline(time.Now().Add(time.Second))
command, _ := bufio.NewReader(conn).ReadString('\n')
if command == "LIST VAR h1000m\n" {
fmt.Fprint(conn, response)
}
conn.Close()
}
}()
address := listener.Addr().String()
for _, expected := range []string{"OL", "NUT: ERR DATA-STALE", "OB LB"} {
values, err := ReadUPS(address, "h1000m", time.Second)
actual := values["ups.status"]
if err != nil {
actual = err.Error()
}
if actual != expected {
t.Fatalf("got %q, want %q", actual, expected)
}
}
}
+27
View File
@@ -0,0 +1,27 @@
package web
import (
_ "embed"
"encoding/json"
"io"
"net/http"
"lan-ups/internal/monitor"
)
//go:embed static/index.html
var dashboard string
func Handler(snapshot func() monitor.Snapshot) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
io.WriteString(w, dashboard)
})
mux.HandleFunc("GET /api/status", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
json.NewEncoder(w).Encode(snapshot())
})
return mux
}
+89
View File
@@ -0,0 +1,89 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>局域网 UPS</title>
<style>
:root { color-scheme: dark; font: 16px system-ui, sans-serif; background: #101720; color: #eef4fa; }
body { margin: 0; }
main { max-width: 860px; margin: 0 auto; padding: clamp(24px, 6vw, 70px) 22px; }
h1 { font-size: clamp(2rem, 5vw, 3.5rem); letter-spacing: -.035em; margin: 0 0 6px; }
p { margin: 0; }
.muted, dt { color: #aab9c8; }
#source, #detail { overflow-wrap: anywhere; }
.status { margin: 30px 0 16px; padding: 22px; background: #182330; border: 1px solid #344658; border-left: 4px solid #82a9cc; border-radius: 10px; }
.status[data-tone="ok"] { border-left-color: #5ed4a8; }
.status[data-tone="warn"] { border-left-color: #ffbd72; }
h2 { margin: 0 0 8px; font-size: 1.3rem; }
#detail:not(:empty) { margin-top: 8px; color: #ffcc91; }
dl { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 0; }
dl div { padding: 18px; border: 1px solid #344658; border-radius: 10px; background: #182330; }
dd { margin: 8px 0 0; font-size: 1.5rem; font-variant-numeric: tabular-nums; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<main>
<h1>局域网 UPS</h1>
<p class="muted" id="source"></p>
<section class="status" id="status" role="status">
<h2 id="headline">正在连接</h2>
<p class="muted" id="lastOK"></p>
<p id="detail"></p>
</section>
<dl id="readings" aria-label="UPS 读数" hidden>
<div><dt>电池电量</dt><dd data-key="battery.charge" data-unit="%"></dd></div>
<div><dt>负载</dt><dd data-key="ups.load" data-unit="%"></dd></div>
<div><dt>输入电压</dt><dd data-key="input.voltage" data-unit=" V"></dd></div>
<div><dt>输出电压</dt><dd data-key="output.voltage" data-unit=" V"></dd></div>
</dl>
</main>
<script>
const source = document.querySelector('#source');
const status = document.querySelector('#status');
const headline = document.querySelector('#headline');
const lastOK = document.querySelector('#lastOK');
const detail = document.querySelector('#detail');
const readings = document.querySelector('#readings');
const metrics = readings.querySelectorAll('[data-key]');
let latest;
function render(snapshot, requestError = '') {
const live = !requestError && snapshot?.health === 'live';
const waiting = !requestError && snapshot?.health === 'waiting';
const flags = (snapshot?.values?.['ups.status'] ?? '').split(/\s+/);
const low = flags.includes('LB');
const battery = flags.includes('OB');
const online = flags.includes('OL');
status.dataset.tone = waiting ? '' : live && online && !low && !battery ? 'ok' : 'warn';
headline.textContent = waiting ? '正在连接' : !live ? '通讯中断' :
low ? '电池电量低' : battery ? '电池供电' : online ? '市电供电' : `UPS 状态 ${flags.join(' ')}`;
source.textContent = snapshot?.source ?? '';
lastOK.textContent = snapshot?.lastOK ?
`${live ? '更新于' : '历史读数 · 最后读取于'} ${new Date(snapshot.lastOK).toLocaleString()}` :
'等待首次有效读数';
detail.textContent = requestError || snapshot?.error || '';
readings.hidden = !snapshot?.values;
for (const metric of metrics) {
const value = snapshot?.values?.[metric.dataset.key];
metric.textContent = value ? value + metric.dataset.unit : '—';
}
}
async function refresh() {
try {
const response = await fetch('/api/status', { signal: AbortSignal.timeout(4000) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
latest = await response.json();
render(latest);
} catch {
render(latest, '无法连接监控服务');
} finally {
setTimeout(refresh, 2000);
}
}
refresh();
</script>
</body>
</html>