Initial LanUps implementation and native installers
This commit is contained in:
commit
67a043c89b
66 files changed
+2870
No files matched your search
@@ -0,0 +1,8 @@
|
||||
* text=auto
|
||||
desktop/deploy/linux/** text eol=lf
|
||||
desktop/deploy/macos/** text eol=lf
|
||||
desktop/deploy/router/** text eol=lf
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
*.ico binary
|
||||
*.png binary
|
||||
@@ -0,0 +1,4 @@
|
||||
/.dotnet/
|
||||
/artifacts/
|
||||
**/bin/
|
||||
**/obj/
|
||||
@@ -0,0 +1,30 @@
|
||||
# 局域网 UPS
|
||||
|
||||
雷迪司 H1000M 通过 USB 连接 LEDE 路由器。路由器运行 NUT 服务端,自研监控通过 `192.168.5.1:3493` 获取状态,并在浏览器内显示。
|
||||
|
||||
## 运行监控
|
||||
|
||||
在本目录使用 Go 1.22 或更新版本运行:
|
||||
|
||||
```sh
|
||||
go run . -nut 192.168.5.1:3493 -ups h1000m
|
||||
```
|
||||
|
||||
打开 `http://127.0.0.1:8080`。程序默认每次查询结束后等待 3 秒再轮询,可用 `-interval 5s` 调整。断线期间页面会标明最后一次成功读取的时间,恢复后自动显示新数据。该版本提供只读监控,自动关机可由设备侧已有的 UPS 客户端负责。
|
||||
|
||||
部署到 Windows 或 NAS 可先运行 `go build .` 生成当前平台的单文件程序。需要从其他局域网设备访问时,使用 `-listen <本机局域网IP>:8080`。页面没有登录功能,适合在受信任的局域网使用。
|
||||
|
||||
## 目录
|
||||
|
||||
| 路径 | 职责 |
|
||||
| --- | --- |
|
||||
| `main.go` | 启动参数、应用入口 |
|
||||
| `internal/nut/` | NUT 协议客户端及测试 |
|
||||
| `internal/monitor/` | 轮询、历史读数和连接状态 |
|
||||
| `internal/web/` | HTTP 接口和嵌入式网页 |
|
||||
| `desktop/` | Avalonia + Semi 桌面客户端、NUT 客户端库和后台程序 |
|
||||
| `docs/` | 部署与进度说明 |
|
||||
|
||||
- [LEDE 路由器部署](docs/lede.md)
|
||||
- [真机验证与群晖评估排程](docs/roadmap.md)
|
||||
- [桌面端构建与关闭行为](desktop/README.md)
|
||||
@@ -0,0 +1,5 @@
|
||||
<Solution>
|
||||
<Project Path="src/LanUps.Core/LanUps.Core.csproj" />
|
||||
<Project Path="src/LanUps.Desktop/LanUps.Desktop.csproj" />
|
||||
<Project Path="src/LanUps.Agent/LanUps.Agent.csproj" />
|
||||
</Solution>
|
||||
@@ -0,0 +1,61 @@
|
||||
# 局域网 UPS 桌面端与系统服务
|
||||
|
||||
Agent 连接 LEDE 上的 NUT,负责轮询、保存服务器配置和处理 `FSD`。Avalonia + Semi 桌面端通过本机 `127.0.0.1:47183` 与 Agent 通信,显示读数、发现 UPS、保存设置并响应关机提醒。接口需要本机凭据文件 `agent.token`,桌面用户只需读取凭据。桌面退出后,系统服务继续工作。
|
||||
|
||||
## 关机确认
|
||||
|
||||
Agent 收到有效的 `FSD` 后开始 60 秒倒计时。已登录用户的桌面程序会从托盘弹出确认框,可立即关机或取消本次。如果用户没有响应,Agent 到时执行关机。通信中断不会触发新的关机;已经收到的关机信号仍按原截止时间处理。截止时间和已处理状态保存在 Agent 本机,便于服务重启后恢复进度并避免同一持续信号重复发起关机。
|
||||
|
||||
Agent 默认运行模拟模式。以 `--enable-shutdown` 启动才执行系统关机程序。系统服务需要相应权限。若尚无人登录,弹窗无法显示,Agent 仍会执行后台策略。
|
||||
|
||||
LEDE 上的 `upsd` 发布读数。要在真实停电时发布 `FSD`,可启用路由器安装器的低电量策略,或手动配置 NUT 主监控。Agent 通过轮询读取 `FSD`。若另有系统负责切断 UPS 输出,应预留至少 60 秒加设备关机所需时间,确保倒计时能完成。
|
||||
|
||||
设置页支持「更新」发现 NUT 名称,还可配置关闭窗口行为。桌面状态日志和关机弹窗事件会写入桌面用户日志。Agent 自身的后台事件写入服务日志,由各平台的服务管理器收集。
|
||||
|
||||
## 开发联调
|
||||
|
||||
使用 .NET 10 SDK。先为两个进程设置同一个 `LANUPS_AGENT_TOKEN` 环境变量,指向当前用户私有目录中的绝对文件路径。在同一个环境执行:
|
||||
|
||||
```sh
|
||||
dotnet run --project src/LanUps.Agent -- --provision
|
||||
dotnet run --project src/LanUps.Agent
|
||||
```
|
||||
|
||||
在另一个继承同样环境变量的终端运行 `dotnet run --project src/LanUps.Desktop`。凭据只需生成一次。联调可保留模拟模式和默认 NUT 地址 `192.168.5.1:3493`,实际验证关机弹窗时使用隔离的模拟 NUT 服务。
|
||||
|
||||
## 发布与开机自启
|
||||
|
||||
### 安装包
|
||||
|
||||
项目根目录下的 `artifacts/native-installers-optimized/` 包含精简版原生安装包及 `SHA256SUMS`。Linux 使用 Native AOT,Windows 和 macOS 使用裁剪后的自包含发布。目标设备均无需单独安装 .NET。旧安装包保留在 `artifacts/native-installers/`。
|
||||
|
||||
### 构建精简版
|
||||
|
||||
在已安装目标平台工具链的**构建机**上运行 `desktop/deploy/package.ps1 -Mode Aot -Targets <RID>`,或者通过 `dotnet publish -c Release -r <RID> --self-contained true -p:PublishAot=true -p:OptimizationPreference=Size` 分别发布 Agent 和 Desktop。Windows 需要 MSVC 原生链接工具,macOS 需要 Xcode 命令行工具,Linux 需要 Clang 和对应架构的系统库。用 `-Mode Trimmed` 可构建同样无需外置运行时的裁剪版本。把各目标的发布结果分别放在 `artifacts/installer-payload-optimized/<RID>/Agent` 和 `Desktop` 后,运行 `desktop/deploy/package.ps1 -Mode Pack` 可一次打包所有平台。DEB 会从实际 ELF 产物记录最低 glibc 版本。
|
||||
|
||||
| 平台 | 安装入口 | 自动配置 |
|
||||
| --- | --- | --- |
|
||||
| OpenWrt / LEDE | `opkg install ./lanups-router_0.1.0-1_all.ipk` | 安装 NUT 依赖,安装后配置 H1000M、LAN 监听和服务自启。UPS 暂不可读时,在下一次 USB 接入时自动重试 |
|
||||
| Windows x64 | 双击 `LanUps-Setup-win-x64.exe` 并确认管理员提示 | 安装到 Program Files,注册 Windows 服务、自启任务和桌面快捷方式 |
|
||||
| Debian / Ubuntu x64 或 ARM64 | 用软件安装器打开 `.deb`,或用 `sudo apt install ./lanups_0.1.0-1_<架构>.deb` | 安装后启用 systemd 服务和应用启动项,授权桌面账户读取本机凭据。首次安装后重新登录使用户组生效 |
|
||||
| macOS Intel / Apple Silicon | 双击对应架构的 `.pkg`,由 macOS 安装器运行安装流程 | 安装 `.app` 和 LaunchDaemon,并为当前已登录用户配置 LaunchAgent。发布包未签名或公证 |
|
||||
|
||||
首次安装默认模拟关机。确认流程后,Windows 可用 `-EnableShutdown` 重新运行 EXE,Linux 和 macOS 可通过服务配置加 `--enable-shutdown`。路由器执行 `lanups-router --enable-fsd` 才启用低电量联动。该模式只在读到 `OB` 和 `LB` 时发布 `FSD`,通信中断不会发布。策略不会主动关闭路由器或切断 UPS 输出。若 UPS 已发出 `FSD`,市电持续恢复约两分钟后,策略会重启 NUT 服务清除锁存状态。启用前应确认电池剩余时间足够覆盖客户端的 60 秒倒计时和关机时间。
|
||||
|
||||
### 手动部署
|
||||
|
||||
使用 `dotnet publish <项目路径> -c Release -r <RID> --self-contained true -o <输出目录>` 分别发布 `src/LanUps.Agent` 和 `src/LanUps.Desktop`。Windows x64 用 `win-x64`,Linux x64 用 `linux-x64`,Apple Silicon 用 `osx-arm64`,Intel Mac 用 `osx-x64`。将系统服务的二进制和配置放到普通用户不可写的目录。
|
||||
|
||||
### Windows
|
||||
|
||||
以管理员身份将发布目录分别放入 `%ProgramFiles%\LanUps\Agent` 和 `%ProgramFiles%\LanUps\Desktop`,然后运行 `deploy/windows/install.ps1 -Operator '<计算机名>\<桌面账号>'`。脚本为指定桌面用户授予本机凭据读取权限,注册自动启动的 Windows 服务,并创建登录时启动托盘程序的计划任务。确认模拟流程后,可在初次注册时另加 `-EnableShutdown`,或在停止服务后把服务启动参数改为 `--enable-shutdown` 再启动。后台日志可在事件查看器中查看,并可按需调整 Windows 事件日志级别。
|
||||
|
||||
### Linux
|
||||
|
||||
以管理员身份把发布目录放入 `/opt/lanups/agent` 和 `/opt/lanups/desktop`,用 `/opt/lanups/agent/LanUps.Agent --provision` 生成 `/etc/LanUps/agent.token`。将凭据的组设为获准操作的用户组并设为 `0640`。目录、其他配置与程序文件由 root 管理。把 `deploy/linux/lanups-agent.service` 放入 `/etc/systemd/system/` 后运行 `systemctl daemon-reload` 和 `systemctl enable --now lanups-agent`。将 `deploy/linux/lanups-desktop.desktop` 放入桌面用户的 `~/.config/autostart/`。需要启用真实关机时,在 systemd 的 `ExecStart` 后加 `--enable-shutdown` 并重启服务。查看后台日志可用 `journalctl -u lanups-agent`。
|
||||
|
||||
### macOS
|
||||
|
||||
以管理员身份把发布目录放入 `/usr/local/libexec/lanups/agent` 和 `/usr/local/libexec/lanups/desktop`,运行 `/usr/local/libexec/lanups/agent/LanUps.Agent --provision`。本机凭据位于 `/Library/Application Support/LanUps/agent.token`,应只给指定桌面用户或授权组读取权限。将 `deploy/macos/local.lanups.agent.plist` 安装到 `/Library/LaunchDaemons/`,由 root 管理,再以系统域加载。将 `deploy/macos/local.lanups.desktop.plist` 安装到桌面用户的 `~/Library/LaunchAgents/`,由该用户在登录会话加载。需要启用真实关机时,在后台 LaunchDaemon 的 `ProgramArguments` 中追加 `--enable-shutdown` 并重载。跨平台发布产物要在目标版本上验收登录启动、权限和通知表现。
|
||||
|
||||
[Go 网页监控仍可独立运行](../README.md)。
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=LAN UPS Agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
ExecStart=/opt/lanups/agent/LanUps.Agent
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,5 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=局域网 UPS
|
||||
Exec=/opt/lanups/desktop/LanUps.Desktop --tray
|
||||
Terminal=false
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
[ "${1:-}" = configure ] || exit 0
|
||||
data=/etc/LanUps
|
||||
token=$data/agent.token
|
||||
group=lanups-operators
|
||||
install -d -m 0755 -o root -g root "$data"
|
||||
getent group "$group" >/dev/null || groupadd --system "$group"
|
||||
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /opt/lanups/agent/LanUps.Agent --provision; fi
|
||||
chown root:"$group" "$token"
|
||||
chmod 0640 "$token"
|
||||
|
||||
operator=${SUDO_USER:-}
|
||||
if [ -z "$operator" ] || [ "$operator" = root ]; then operator=$(getent passwd 1000 | cut -d: -f1); fi
|
||||
if [ -n "$operator" ] && [ "$(id -u "$operator")" -ge 1000 ]; then usermod -a -G "$group" "$operator"; fi
|
||||
|
||||
if command -v systemctl >/dev/null; then
|
||||
systemctl enable lanups-agent.service
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl daemon-reload
|
||||
deb-systemd-invoke restart lanups-agent.service
|
||||
fi
|
||||
fi
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null; then systemctl daemon-reload; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ "${1:-}" = remove ] && command -v systemctl >/dev/null; then
|
||||
if [ -d /run/systemd/system ]; then deb-systemd-invoke stop lanups-agent.service || :; fi
|
||||
systemctl disable lanups-agent.service || :
|
||||
fi
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
[ -r /etc/LanUps/agent.token ] || exit 0
|
||||
exec /opt/lanups/desktop/LanUps.Desktop --tray
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>local.lanups.agent</string>
|
||||
<key>ProgramArguments</key><array><string>/usr/local/libexec/lanups/agent/LanUps.Agent</string></array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>Umask</key><integer>63</integer>
|
||||
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
||||
<key>StandardOutPath</key><string>/var/log/lanups-agent.log</string>
|
||||
<key>StandardErrorPath</key><string>/var/log/lanups-agent-error.log</string>
|
||||
</dict></plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>local.lanups.desktop</string>
|
||||
<key>ProgramArguments</key><array><string>/Applications/LanUps.app/Contents/MacOS/LanUps.Desktop</string><string>--tray</string></array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>LimitLoadToSessionType</key><string>Aqua</string>
|
||||
</dict></plist>
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
data='/Library/Application Support/LanUps'
|
||||
token="$data/agent.token"
|
||||
install -d -m 0755 -o root -g wheel "$data"
|
||||
if [ ! -f "$token" ]; then LANUPS_AGENT_TOKEN="$token" /usr/local/libexec/lanups/agent/LanUps.Agent --provision; fi
|
||||
chmod 0600 "$token"
|
||||
|
||||
user=$(/usr/bin/stat -f '%Su' /dev/console)
|
||||
case "$user" in root|loginwindow|_mbsetupuser|'') user='';; esac
|
||||
if [ -n "$user" ]; then
|
||||
uid=$(id -u "$user")
|
||||
home=$(/usr/bin/dscl . -read "/Users/$user" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
|
||||
case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac
|
||||
chmod -N "$token"
|
||||
chmod +a "user:$user allow read" "$token"
|
||||
sudo -u "$user" mkdir -p "$home/Library/LaunchAgents"
|
||||
sudo -u "$user" install -m 0644 /usr/local/libexec/lanups/local.lanups.desktop.plist "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
|
||||
launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if [ -n "$user" ] && launchctl print "gui/$uid" >/dev/null 2>&1; then
|
||||
launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
[ "${3:-/}" = / ] || { echo 'Install LanUps onto the running macOS system volume.' >&2; exit 1; }
|
||||
if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi
|
||||
user=$(/usr/bin/stat -f '%Su' /dev/console)
|
||||
case "$user" in root|loginwindow|_mbsetupuser|'') exit 0;; esac
|
||||
uid=$(id -u "$user")
|
||||
if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi
|
||||
@@ -0,0 +1,5 @@
|
||||
module lan-ups-macos-packager
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require go.digitalxero.dev/osx v0.3.0
|
||||
@@ -0,0 +1,16 @@
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/github/smimesign v0.2.0 h1:Hho4YcX5N1I9XNqhq0fNx0Sts8MhLonHd+HRXVGNjvk=
|
||||
github.com/github/smimesign v0.2.0/go.mod h1:iZiiwNT4HbtGRVqCQu7uJPEZCuEE5sfSSttcnePkDl4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.digitalxero.dev/osx v0.3.0 h1:PwlFuyUEcT5/4HxHAf1DjHaCRZuVcrQkC7W0yvL8k8E=
|
||||
go.digitalxero.dev/osx v0.3.0/go.mod h1:RndPJgzpTmsGwHBK6mU9KmQq5F+YgPHn/FjETzvc230=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0 h1:Db8W44cB54TWD7stUFFSWxdfpdn6fZVcDl0w3R4RVM0=
|
||||
software.sslmate.com/src/go-pkcs12 v0.7.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
|
||||
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"go.digitalxero.dev/osx/pkg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 6 {
|
||||
log.Fatal("usage: macpack payload preinstall postinstall architecture output.pkg")
|
||||
}
|
||||
root, prePath, postPath, architecture, output := os.Args[1], os.Args[2], os.Args[3], os.Args[4], os.Args[5]
|
||||
if architecture != pkg.ArchARM64 && architecture != pkg.ArchX8664 {
|
||||
log.Fatal("invalid macOS architecture")
|
||||
}
|
||||
pre, err := os.ReadFile(prePath)
|
||||
check(err)
|
||||
post, err := os.ReadFile(postPath)
|
||||
check(err)
|
||||
component := pkg.NewPackage().WithIdentifier("local.lanups").WithName("LanUps").WithVersion("0.1.0").
|
||||
WithPreInstallScript(pre).WithPostInstallScript(post)
|
||||
check(filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil || entry.IsDir() {
|
||||
return err
|
||||
}
|
||||
relative, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := filepath.ToSlash(relative)
|
||||
mode := fs.FileMode(0o644)
|
||||
if strings.HasSuffix(name, "/LanUps.Agent") || strings.HasSuffix(name, "/LanUps.Desktop") {
|
||||
mode = 0o755
|
||||
}
|
||||
component.WithFileFromPath("/"+name, path).WithMode(mode).Add()
|
||||
return nil
|
||||
}))
|
||||
product, err := pkg.NewProduct().WithTitle("LanUps").WithIdentifier("local.lanups.product").WithVersion("0.1.0").
|
||||
WithHostArchitectures(architecture).WithMinOSVersion("15.0").WithComponent(component).Build()
|
||||
check(err)
|
||||
file, err := os.Create(output)
|
||||
check(err)
|
||||
_, err = product.WriteTo(file)
|
||||
check(err)
|
||||
check(file.Close())
|
||||
|
||||
file, err = os.Open(output)
|
||||
check(err)
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
check(err)
|
||||
archive, err := pkg.Open(file, info.Size())
|
||||
check(err)
|
||||
check(archive.Verify())
|
||||
installed, err := archive.Component("local.lanups")
|
||||
check(err)
|
||||
check(installed.Verify())
|
||||
}
|
||||
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "LanUps installation failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
archive, err := zip.OpenReader(self)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
stage, err := os.MkdirTemp("", "LanUps-Setup-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(stage)
|
||||
for _, entry := range archive.File {
|
||||
path := filepath.FromSlash(entry.Name)
|
||||
if !fs.ValidPath(entry.Name) || !filepath.IsLocal(path) || !entry.Mode().IsRegular() {
|
||||
return fmt.Errorf("invalid installer entry: %q", entry.Name)
|
||||
}
|
||||
if err := extract(filepath.Join(stage, path), entry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(os.Args) == 2 && os.Args[1] == "--verify" {
|
||||
fmt.Printf("Verified %d installer files\n", len(archive.File))
|
||||
return nil
|
||||
}
|
||||
setup := filepath.Join(stage, "Setup.ps1")
|
||||
args := append([]string{"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", setup}, os.Args[1:]...)
|
||||
powershell := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
||||
command := exec.Command(powershell, args...)
|
||||
command.Stdout, command.Stderr = os.Stdout, os.Stderr
|
||||
return command.Run()
|
||||
}
|
||||
|
||||
func extract(path string, entry *zip.File) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
input, err := entry.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer input.Close()
|
||||
output, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(output, input)
|
||||
closeErr := output.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Build native system installers from the LanUps publish payloads."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from package import DEPLOY, ICON, ROOT, binaries, tar_bytes, windows_package
|
||||
|
||||
NATIVE = DEPLOY / 'native'
|
||||
OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve()
|
||||
|
||||
|
||||
def script(path):
|
||||
return path.read_bytes().replace(b'\r\n', b'\n')
|
||||
|
||||
|
||||
def tar_parents(archive, name, known):
|
||||
parts = name.removeprefix('./').split('/')[:-1]
|
||||
for length in range(1, len(parts) + 1):
|
||||
path = './' + '/'.join(parts[:length])
|
||||
if path not in known:
|
||||
directory = tarfile.TarInfo(path)
|
||||
directory.type = tarfile.DIRTYPE
|
||||
directory.mode = 0o755
|
||||
archive.addfile(directory)
|
||||
known.add(path)
|
||||
|
||||
|
||||
def router_package():
|
||||
source = DEPLOY / 'router'
|
||||
control, data = io.BytesIO(), io.BytesIO()
|
||||
with tarfile.open(fileobj=control, mode='w:gz') as archive:
|
||||
for name in ('control', 'postinst', 'prerm'):
|
||||
tar_bytes(archive, './' + name, script(source / name), 0o644 if name == 'control' else 0o755)
|
||||
with tarfile.open(fileobj=data, mode='w:gz') as archive:
|
||||
directories = set()
|
||||
for source_name, name in {
|
||||
'install.sh': './usr/lib/lanups-router/install.sh',
|
||||
'lanups-policy': './usr/sbin/lanups-policy',
|
||||
'lanups-fsd.init': './etc/init.d/lanups-fsd',
|
||||
'lanups-router': './usr/sbin/lanups-router',
|
||||
'lanups-hotplug': './etc/hotplug.d/usb/95-lanups-router',
|
||||
}.items():
|
||||
tar_parents(archive, name, directories)
|
||||
tar_bytes(archive, name, script(source / source_name), 0o755)
|
||||
path = OUTPUT / 'lanups-router_0.1.0-1_all.ipk'
|
||||
with tarfile.open(path, 'w:gz') as archive:
|
||||
for name, value in (('debian-binary', b'2.0\n'), ('control.tar.gz', control.getvalue()), ('data.tar.gz', data.getvalue())):
|
||||
tar_bytes(archive, './' + name, value, 0o644)
|
||||
return path
|
||||
|
||||
|
||||
def write_ar_member(output, name, data):
|
||||
size = len(data) if isinstance(data, bytes) else data.stat().st_size
|
||||
output.write(f'{name + "/":16s}{0:<12d}{0:<6d}{0:<6d}{"100644":8s}{size:<10d}`\n'.encode('ascii'))
|
||||
if isinstance(data, bytes):
|
||||
output.write(data)
|
||||
else:
|
||||
with data.open('rb') as stream:
|
||||
shutil.copyfileobj(stream, output)
|
||||
if size % 2:
|
||||
output.write(b'\n')
|
||||
|
||||
|
||||
def linux_package(rid, stage):
|
||||
source = DEPLOY / 'linux'
|
||||
architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
|
||||
control, data = stage / 'control.tar.gz', stage / 'data.tar.gz'
|
||||
libc_version = (0, 0, 0)
|
||||
with tarfile.open(data, 'w:gz', compresslevel=5) as archive:
|
||||
directories = set()
|
||||
for kind in ('Agent', 'Desktop'):
|
||||
for path, name, executable in binaries(rid, kind):
|
||||
if executable or path.suffix == '.so':
|
||||
contents = path.read_bytes()
|
||||
if contents.startswith(b'\x7fELF'):
|
||||
for major, minor, patch in re.findall(rb'GLIBC_(\d+)\.(\d+)(?:\.(\d+))?\x00', contents):
|
||||
libc_version = max(libc_version, (int(major), int(minor), int(patch or b'0')))
|
||||
item = tarfile.TarInfo(f'./opt/lanups/{kind.lower()}/{name}')
|
||||
tar_parents(archive, item.name, directories)
|
||||
item.size = path.stat().st_size
|
||||
item.mode = 0o755 if executable else 0o644
|
||||
with path.open('rb') as stream:
|
||||
archive.addfile(item, stream)
|
||||
launcher = script(source / 'lanups-desktop.desktop') + b'Icon=lanups\n'
|
||||
for name, content, mode in (
|
||||
('./lib/systemd/system/lanups-agent.service', script(source / 'lanups-agent.service'), 0o644),
|
||||
('./etc/xdg/autostart/lanups-desktop.desktop', launcher.replace(b'/opt/lanups/desktop/LanUps.Desktop --tray', b'/usr/lib/lanups/start-desktop'), 0o644),
|
||||
('./usr/lib/lanups/start-desktop', script(source/'start-desktop'), 0o755),
|
||||
('./usr/share/applications/lanups-desktop.desktop', launcher.replace(b' --tray', b''), 0o644),
|
||||
('./usr/share/icons/hicolor/256x256/apps/lanups.png', ICON.read_bytes(), 0o644),
|
||||
):
|
||||
tar_parents(archive, name, directories)
|
||||
tar_bytes(archive, name, content, mode)
|
||||
libc = 'libc6'
|
||||
if libc_version[0]:
|
||||
version = '.'.join(str(part) for part in (libc_version if libc_version[2] else libc_version[:2]))
|
||||
libc = f'libc6 (>= {version})'
|
||||
metadata = (
|
||||
'Package: lanups\nVersion: 0.1.0-1\n' f'Architecture: {architecture}\n'
|
||||
'Maintainer: LanUps Project\nSection: utils\nPriority: optional\n'
|
||||
f'Depends: adduser, passwd, init-system-helpers, {libc}, libgcc-s1, libstdc++6, libssl3 | libssl3t64, libx11-6, libx11-xcb1, libxcb1, libxext6, libxi6, libxrandr2, libice6, libsm6, libfontconfig1, libgl1, libicu72 | libicu74 | libicu76 | libicu77 | libicu78\n'
|
||||
'Description: LAN UPS Agent and desktop monitor\n'
|
||||
)
|
||||
with tarfile.open(control, 'w:gz') as archive:
|
||||
tar_bytes(archive, './control', metadata.encode(), 0o644)
|
||||
for name in ('postinst', 'prerm', 'postrm'):
|
||||
tar_bytes(archive, './'+name, script(source / name), 0o755)
|
||||
path = OUTPUT / f'lanups_0.1.0-1_{architecture}.deb'
|
||||
with path.open('wb') as output:
|
||||
output.write(b'!<arch>\n')
|
||||
for name, payload in (('debian-binary', b'2.0\n'), ('control.tar.gz', control), ('data.tar.gz', data)):
|
||||
write_ar_member(output, name, payload)
|
||||
control.unlink()
|
||||
data.unlink()
|
||||
return path
|
||||
|
||||
|
||||
def mac_package(rid, stage, builder):
|
||||
source = DEPLOY / 'macos'
|
||||
payload = stage / rid
|
||||
for kind in ('Agent','Desktop'):
|
||||
prefix = 'usr/local/libexec/lanups/agent' if kind == 'Agent' else 'Applications/LanUps.app/Contents/MacOS'
|
||||
for path, name, executable in binaries(rid, kind):
|
||||
destination = payload / prefix / name
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination)
|
||||
bundle = payload / 'Applications/LanUps.app/Contents'
|
||||
(bundle / 'Resources').mkdir()
|
||||
plist = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
|
||||
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
|
||||
CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
|
||||
(bundle / 'Info.plist').write_bytes(plistlib.dumps(plist))
|
||||
icon = ICON.read_bytes()
|
||||
(bundle / 'Resources/ups.icns').write_bytes(b'icns' + struct.pack('>I', len(icon)+16) + b'ic08' + struct.pack('>I', len(icon)+8) + icon)
|
||||
for path, location in (('local.lanups.agent.plist','Library/LaunchDaemons'), ('local.lanups.desktop.plist','usr/local/libexec/lanups')):
|
||||
target = payload / location / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(script(source / path))
|
||||
for name in ('preinstall', 'postinstall'):
|
||||
(stage / name).write_bytes(script(source / name))
|
||||
output = OUTPUT / f'LanUps-{rid}.pkg'
|
||||
subprocess.run([str(builder), str(payload), str(stage/'preinstall'), str(stage/'postinstall'),
|
||||
'arm64' if rid == 'osx-arm64' else 'x86_64', str(output)], check=True)
|
||||
return output
|
||||
|
||||
|
||||
def main(targets):
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
packages = [router_package()]
|
||||
with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp:
|
||||
stage = Path(temp)
|
||||
extension = '.exe' if os.name == 'nt' else ''
|
||||
builder = stage / ('macpack' + extension)
|
||||
if any(rid.startswith('osx-') for rid in targets):
|
||||
subprocess.run(['go','build','-mod=readonly','-trimpath','-o',str(builder),'.'],cwd=NATIVE/'macos',check=True)
|
||||
for rid in targets:
|
||||
if rid.startswith('linux-'):
|
||||
output = linux_package(rid, stage)
|
||||
elif rid.startswith('osx-'):
|
||||
output = mac_package(rid, stage, builder)
|
||||
elif rid == 'win-x64':
|
||||
stub = stage / 'setup.exe'
|
||||
env = dict(os.environ, GOOS='windows', GOARCH='amd64', CGO_ENABLED='0')
|
||||
subprocess.run(['go','build','-trimpath','-ldflags=-s -w','-o',str(stub),str(NATIVE/'windows/main.go')],cwd=ROOT,env=env,check=True)
|
||||
payload = windows_package(rid, stage / 'windows-payload.zip')
|
||||
output = OUTPUT / 'LanUps-Setup-win-x64.exe'
|
||||
with output.open('wb') as stream:
|
||||
for part in (stub,payload):
|
||||
with part.open('rb') as file:
|
||||
shutil.copyfileobj(file, stream)
|
||||
if os.name == 'nt':
|
||||
subprocess.run([str(output),'--verify'],check=True)
|
||||
else:
|
||||
raise ValueError(f'Unsupported target: {rid}')
|
||||
packages.append(output)
|
||||
print(output.name, flush=True)
|
||||
archives = [path for path in OUTPUT.iterdir() if path.suffix in {'.exe', '.deb', '.pkg', '.ipk'}]
|
||||
with (OUTPUT / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
|
||||
for path in sorted(archives):
|
||||
with path.open('rb') as stream:
|
||||
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
|
||||
print(packages[0].name, flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,40 @@
|
||||
param(
|
||||
[string[]]$Targets = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64'),
|
||||
[ValidateSet('Aot','Trimmed','Pack')][string]$Mode = 'Pack'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$localDotnet = Join-Path $root '.dotnet\dotnet.exe'
|
||||
$dotnet = if (Test-Path -LiteralPath $localDotnet) { $localDotnet } else { (Get-Command dotnet -ErrorAction Stop).Source }
|
||||
if (Test-Path -LiteralPath $localDotnet) {
|
||||
$env:DOTNET_CLI_HOME = Join-Path $root '.dotnet'
|
||||
$env:NUGET_PACKAGES = Join-Path $env:DOTNET_CLI_HOME 'packages'
|
||||
}
|
||||
$allowed = @('win-x64','linux-x64','linux-arm64','osx-x64','osx-arm64')
|
||||
$platform = if ($IsWindows -or $env:OS -eq 'Windows_NT') { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' }
|
||||
$payload = if ($env:LANUPS_INSTALLER_PAYLOAD) { $env:LANUPS_INSTALLER_PAYLOAD } else { Join-Path $root 'artifacts\installer-payload-optimized' }
|
||||
foreach ($rid in $Targets) {
|
||||
if ($rid -notin $allowed) { throw "Unsupported target: $rid" }
|
||||
if ($Mode -eq 'Pack') { continue }
|
||||
if ($Mode -eq 'Aot' -and !$rid.StartsWith("$platform-")) { throw "Native AOT for $rid must be built on a $($rid.Split('-')[0]) host" }
|
||||
$publish = if ($Mode -eq 'Aot') { @('-p:PublishAot=true','-p:OptimizationPreference=Size') } else { @('-p:PublishTrimmed=true') }
|
||||
foreach ($kind in @('Agent','Desktop')) {
|
||||
$project = Join-Path $root "desktop\src\LanUps.$kind\LanUps.$kind.csproj"
|
||||
$output = Join-Path $payload "$rid\$kind"
|
||||
$temporary = "$output.$([guid]::NewGuid()).publish"
|
||||
& $dotnet publish $project -c Release -r $rid --self-contained true @publish --disable-build-servers -o $temporary -v minimal
|
||||
if ($LASTEXITCODE) { exit $LASTEXITCODE }
|
||||
if (Test-Path -LiteralPath $output) {
|
||||
$backup = "$output.$([guid]::NewGuid()).previous"
|
||||
Move-Item -LiteralPath $output -Destination $backup
|
||||
try { Move-Item -LiteralPath $temporary -Destination $output } catch { Move-Item -LiteralPath $backup -Destination $output; throw }
|
||||
$resolvedBackup = (Resolve-Path -LiteralPath $backup).Path
|
||||
$resolvedParent = (Resolve-Path -LiteralPath (Split-Path -Parent $output)).Path
|
||||
if ((Split-Path -Parent $resolvedBackup) -eq $resolvedParent -and (Split-Path -Leaf $resolvedBackup) -like "$kind.*.previous") {
|
||||
Remove-Item -LiteralPath $resolvedBackup -Recurse -Force
|
||||
}
|
||||
} else { Move-Item -LiteralPath $temporary -Destination $output }
|
||||
}
|
||||
}
|
||||
& python (Join-Path $PSScriptRoot 'native_packages.py') @Targets
|
||||
exit $LASTEXITCODE
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Assemble installable archives from self-contained dotnet publish output."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import struct
|
||||
import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
DEPLOY = Path(__file__).resolve().parent
|
||||
ROOT = DEPLOY.parent.parent
|
||||
PAYLOAD = Path(os.environ.get('LANUPS_INSTALLER_PAYLOAD', ROOT / 'artifacts' / 'installer-payload-optimized')).resolve()
|
||||
DIST = ROOT / 'artifacts' / 'installers'
|
||||
ICON = DEPLOY.parent / 'src' / 'LanUps.Desktop' / 'Assets' / 'ups.png'
|
||||
|
||||
|
||||
def binaries(rid, kind):
|
||||
directory = PAYLOAD / rid / kind
|
||||
executable = directory / f"LanUps.{kind}{'.exe' if rid.startswith('win-') else ''}"
|
||||
if not executable.is_file():
|
||||
raise FileNotFoundError(executable)
|
||||
for path in sorted(directory.rglob('*')):
|
||||
if path.is_file() and path.suffix.lower() not in {'.pdb', '.dbg'} and not any(part.endswith('.dSYM') for part in path.parts):
|
||||
yield path, path.relative_to(directory).as_posix(), path == executable
|
||||
|
||||
|
||||
def tar_bytes(archive, name, data, mode):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size = len(data)
|
||||
item.mode = mode
|
||||
archive.addfile(item, io.BytesIO(data))
|
||||
|
||||
|
||||
def unix_package(rid):
|
||||
mac = rid.startswith('osx-')
|
||||
path = DIST / f'LanUps-{rid}.tar.gz'
|
||||
with tarfile.open(path, 'w:gz', compresslevel=5) as archive:
|
||||
tar_bytes(archive, 'install.sh', (DEPLOY / 'unix' / 'install.sh').read_bytes().replace(b'\r\n', b'\n'), 0o755)
|
||||
tar_bytes(archive, 'architecture', rid.split('-', 1)[1].encode() + b'\n', 0o644)
|
||||
folder = DEPLOY / ('macos' if mac else 'linux')
|
||||
for sidecar in sorted(folder.iterdir()):
|
||||
tar_bytes(archive, sidecar.name, sidecar.read_bytes(), 0o644)
|
||||
for kind in ('Agent', 'Desktop'):
|
||||
prefix = 'LanUps.app/Contents/MacOS' if mac and kind == 'Desktop' else kind.lower()
|
||||
for source, filename, executable in binaries(rid, kind):
|
||||
item = tarfile.TarInfo(f'{prefix}/{filename}')
|
||||
item.size = source.stat().st_size
|
||||
item.mode = 0o755 if executable else 0o644
|
||||
with source.open('rb') as stream:
|
||||
archive.addfile(item, stream)
|
||||
if mac:
|
||||
info = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop',
|
||||
CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL',
|
||||
CFBundleIconFile='ups.icns', CFBundleVersion='1', CFBundleShortVersionString='0.1.0')
|
||||
tar_bytes(archive, 'LanUps.app/Contents/Info.plist', plistlib.dumps(info), 0o644)
|
||||
png = ICON.read_bytes()
|
||||
image = b'icns' + struct.pack('>I', len(png) + 16) + b'ic08' + struct.pack('>I', len(png) + 8) + png
|
||||
tar_bytes(archive, 'LanUps.app/Contents/Resources/ups.icns', image, 0o644)
|
||||
else:
|
||||
tar_bytes(archive, 'ups.png', ICON.read_bytes(), 0o644)
|
||||
return path
|
||||
|
||||
|
||||
def windows_package(rid, path=None):
|
||||
path = path or DIST / f'LanUps-{rid}.zip'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED, compresslevel=5) as archive:
|
||||
for filename in ('Setup.cmd', 'Setup.ps1', 'install.ps1'):
|
||||
script = (DEPLOY / 'windows' / filename).read_text(encoding='utf-8-sig')
|
||||
archive.writestr(filename, script.replace('\n', '\r\n').encode('utf-8-sig' if filename.endswith('.ps1') else 'ascii'))
|
||||
for kind in ('Agent', 'Desktop'):
|
||||
for source, filename, _ in binaries(rid, kind):
|
||||
archive.write(source, f'{kind}/{filename}')
|
||||
return path
|
||||
|
||||
|
||||
def main(targets):
|
||||
DIST.mkdir(parents=True, exist_ok=True)
|
||||
router = DIST / 'LanUps-openwrt.tar.gz'
|
||||
with tarfile.open(router, 'w:gz') as archive:
|
||||
for source in sorted((DEPLOY / 'router').iterdir()):
|
||||
tar_bytes(archive, source.name, source.read_bytes().replace(b'\r\n', b'\n'), 0o755)
|
||||
print(router.name, flush=True)
|
||||
for rid in targets:
|
||||
path = windows_package(rid) if rid.startswith('win-') else unix_package(rid)
|
||||
print(path.name, flush=True)
|
||||
archives = sorted([*DIST.glob('LanUps-*.zip'), *DIST.glob('LanUps-*.tar.gz')])
|
||||
with (DIST / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
|
||||
for path in archives:
|
||||
with path.open('rb') as stream:
|
||||
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,8 @@
|
||||
Package: lanups-router
|
||||
Version: 0.1.0-1
|
||||
Architecture: all
|
||||
Maintainer: LanUps Project
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Depends: nut-server, nut-driver-blazer_usb, nut-upsc
|
||||
Description: LAN UPS configuration and optional low-battery policy for OpenWrt
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
mode=read-only
|
||||
case "${1:-}" in
|
||||
'') ;;
|
||||
--enable-fsd) mode=fsd ;;
|
||||
--check) mode=check ;;
|
||||
*) echo 'Usage: sh install.sh [--check|--enable-fsd]' >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$(id -u)" = 0 ] && command -v uci >/dev/null || { echo 'Run as root on OpenWrt/LEDE' >&2; exit 1; }
|
||||
base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
lan=$(uci -q get network.lan.ipaddr | cut -d/ -f1)
|
||||
case "$lan" in ''|*[!0-9.]*) echo 'A static LAN IPv4 address is required' >&2; exit 1;; esac
|
||||
|
||||
usb=''
|
||||
for device in /sys/bus/usb/devices/*; do
|
||||
if [ -r "$device/idVendor" ] && [ "$(cat "$device/idVendor"):$(cat "$device/idProduct")" = 0665:5161 ]; then
|
||||
usb=$(sed -n 's/^DEVNAME=//p' "$device/uevent")
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$usb" ] || { echo 'Connect the H1000M USB device (0665:5161) before installing' >&2; exit 1; }
|
||||
if [ "$mode" = check ]; then
|
||||
echo "LAN $lan; UPS USB 0665:5161 ($usb)"
|
||||
if command -v upsc >/dev/null; then upsc h1000m@127.0.0.1 ups.status || echo 'Current UPS data is unavailable'; fi
|
||||
exit 0
|
||||
fi
|
||||
[ -z "$(uci -q changes nut_server || :)" ] || { echo 'Commit or discard pending nut_server edits before installing' >&2; exit 1; }
|
||||
|
||||
if [ "${LANUPS_SKIP_PACKAGES:-0}" = 1 ]; then
|
||||
command -v upsc >/dev/null && [ -x /etc/init.d/nut-server ] || { echo 'NUT package dependencies are not ready' >&2; exit 1; }
|
||||
elif command -v opkg >/dev/null; then
|
||||
missing=''
|
||||
packages='nut-server nut-driver-blazer_usb nut-upsc'
|
||||
if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then packages="$packages coreutils-timeout"; fi
|
||||
for package in $packages; do
|
||||
if ! opkg list-installed "$package" | grep -q "^$package - "; then missing="$missing $package"; fi
|
||||
done
|
||||
if [ -n "$missing" ]; then
|
||||
opkg update || echo 'Some feeds did not refresh; trying available indexes' >&2
|
||||
# Package names are constants defined above.
|
||||
opkg install $missing
|
||||
fi
|
||||
elif command -v apk >/dev/null; then
|
||||
apk add nut-server nut-driver-blazer_usb nut-upsc
|
||||
if [ "$mode" = fsd ] && ! command -v timeout >/dev/null; then apk add coreutils-timeout; fi
|
||||
else
|
||||
echo 'No supported OpenWrt package manager found' >&2; exit 1
|
||||
fi
|
||||
|
||||
umask 077
|
||||
mkdir -p /etc/lanups
|
||||
backup=$(mktemp /etc/lanups/nut-server.XXXXXX)
|
||||
cp /etc/config/nut_server "$backup"
|
||||
changed=1
|
||||
if [ "$(uci -q get nut_server.h1000m.driver || :)" = blazer_usb ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.port || :)" = auto ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.vendorid || :)" = 0665 ] &&
|
||||
[ "$(uci -q get nut_server.h1000m.productid || :)" = 5161 ] &&
|
||||
uci show nut_server | grep -Fq ".address='$lan'" &&
|
||||
uci show nut_server | grep -Fq ".address='127.0.0.1'"; then
|
||||
changed=0
|
||||
fi
|
||||
|
||||
if [ "$changed" = 1 ]; then
|
||||
uci set nut_server.h1000m=driver
|
||||
uci set nut_server.h1000m.driver=blazer_usb
|
||||
uci set nut_server.h1000m.port=auto
|
||||
uci set nut_server.h1000m.vendorid=0665
|
||||
uci set nut_server.h1000m.productid=5161
|
||||
for entry in "lanups_local:127.0.0.1" "lanups_lan:$lan"; do
|
||||
section=${entry%%:*}; ip=${entry#*:}
|
||||
if ! uci show nut_server | grep -Fq ".address='$ip'"; then
|
||||
uci set "nut_server.$section=listen_address"
|
||||
uci set "nut_server.$section.address=$ip"
|
||||
uci set "nut_server.$section.port=3493"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ "$mode" = fsd ]; then
|
||||
command -v timeout >/dev/null && command -v nc >/dev/null || { echo 'FSD mode requires timeout and nc' >&2; uci revert nut_server; exit 1; }
|
||||
password=$(uci -q get nut_server.lanups_policy.password || :)
|
||||
if [ -z "$password" ]; then password=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n'); fi
|
||||
case "$password" in ''|*[!A-Fa-f0-9]*) echo 'Invalid FSD service credential' >&2; uci revert nut_server; exit 1;; esac
|
||||
uci set nut_server.lanups_policy=user
|
||||
uci set nut_server.lanups_policy.username=lanups_policy
|
||||
uci set "nut_server.lanups_policy.password=$password"
|
||||
uci set nut_server.lanups_policy.actions=FSD
|
||||
changed=1
|
||||
fi
|
||||
|
||||
chown nut:nut "/dev/$usb"
|
||||
chmod 0660 "/dev/$usb"
|
||||
if [ "$changed" = 1 ]; then uci commit nut_server; fi
|
||||
if [ "$mode" = fsd ]; then chmod 0600 /etc/config/nut_server; fi
|
||||
if [ "$changed" = 1 ] || ! /etc/init.d/nut-server running || ! upsc h1000m@127.0.0.1 ups.status >/dev/null 2>&1; then
|
||||
/etc/init.d/nut-server restart
|
||||
fi
|
||||
state=''
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null) && break
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$state" ]; then
|
||||
if [ "$changed" = 1 ]; then cp "$backup" /etc/config/nut_server; /etc/init.d/nut-server restart || :; fi
|
||||
echo "NUT could not read H1000M; backup: $backup" >&2
|
||||
exit 1
|
||||
fi
|
||||
/etc/init.d/nut-server enable
|
||||
if [ "$mode" = fsd ]; then
|
||||
if [ "$base" != /usr/lib/lanups-router ]; then
|
||||
cp "$base/lanups-policy" /usr/sbin/lanups-policy
|
||||
cp "$base/lanups-fsd.init" /etc/init.d/lanups-fsd
|
||||
fi
|
||||
chmod 0755 /usr/sbin/lanups-policy /etc/init.d/lanups-fsd
|
||||
/etc/init.d/lanups-fsd enable
|
||||
/etc/init.d/lanups-fsd restart
|
||||
fi
|
||||
echo "NUT ready: h1000m@$lan:3493 ($state); installer mode: $mode; backup: $backup"
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
START=83
|
||||
STOP=27
|
||||
USE_PROCD=1
|
||||
|
||||
start_service() {
|
||||
procd_open_instance
|
||||
procd_set_param command /usr/sbin/lanups-policy
|
||||
procd_set_param respawn
|
||||
procd_close_instance
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# Sourced by OpenWrt hotplug. A separate process owns the retry lock.
|
||||
case "${ACTION:-}:${PRODUCT:-}" in
|
||||
add:665/5161/*|add:0665/5161/*)
|
||||
if [ -f /etc/lanups/pending ] && [ -n "${DEVNAME:-}" ]; then
|
||||
(
|
||||
lock=/var/run/lanups-router-setup.lock
|
||||
mkdir "$lock" 2>/dev/null || exit 0
|
||||
trap 'rmdir "$lock"' EXIT
|
||||
sleep 2
|
||||
LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router 2>&1 | logger -t lanups-router
|
||||
) </dev/null >/dev/null 2>&1 &
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
online_since=0
|
||||
while :; do
|
||||
if state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null); then
|
||||
case " $state " in
|
||||
*' FSD '*)
|
||||
case " $state " in
|
||||
*' OL '*)
|
||||
read -r uptime _ </proc/uptime
|
||||
now=${uptime%%.*}
|
||||
[ "$online_since" -ne 0 ] || online_since=$now
|
||||
if [ "$((now-online_since))" -ge 120 ]; then
|
||||
# upsd latches FSD. Restart it only after a stable return to mains.
|
||||
/etc/init.d/nut-server restart
|
||||
online_since=0
|
||||
fi
|
||||
;;
|
||||
*) online_since=0 ;;
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
online_since=0
|
||||
case " $state " in
|
||||
*' OB '*) case " $state " in
|
||||
*' LB '*)
|
||||
password=$(uci -q get nut_server.lanups_policy.password)
|
||||
if { printf 'USERNAME lanups_policy\nPASSWORD %s\nFSD h1000m\n' "$password"; sleep 1; } |
|
||||
timeout 5 nc 127.0.0.1 3493 | grep -q '^OK FSD-SET'; then
|
||||
logger -t lanups-fsd 'Published FSD after on-battery and low-battery status'
|
||||
fi
|
||||
;;
|
||||
esac ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
else
|
||||
online_since=0
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
if [ "${1:-}" = --check ]; then exec /bin/sh /usr/lib/lanups-router/install.sh "$@"; fi
|
||||
/bin/sh /usr/lib/lanups-router/install.sh "$@" || exit $?
|
||||
rm -f /etc/lanups/pending
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
[ -z "${IPKG_INSTROOT:-}" ] || exit 0
|
||||
if ! LANUPS_SKIP_PACKAGES=1 /usr/sbin/lanups-router; then
|
||||
mkdir -p /etc/lanups
|
||||
touch /etc/lanups/pending
|
||||
echo 'LanUps package installed; UPS setup will retry automatically when the USB cable is reconnected.' >&2
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
[ -z "${IPKG_INSTROOT:-}" ] || exit 0
|
||||
[ "${1:-remove}" = remove ] || exit 0
|
||||
if [ -x /etc/init.d/lanups-fsd ]; then
|
||||
/etc/init.d/lanups-fsd stop 2>/dev/null || :
|
||||
/etc/init.d/lanups-fsd disable 2>/dev/null || :
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
operator=${SUDO_USER:-}
|
||||
mode=simulation
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--user) [ "$#" -ge 2 ] || exit 2; operator=$2; shift 2;;
|
||||
--enable-shutdown) mode=shutdown; shift;;
|
||||
*) echo 'Usage: sudo sh install.sh [--user ACCOUNT] [--enable-shutdown]' >&2; exit 2;;
|
||||
esac
|
||||
done
|
||||
[ "$(id -u)" = 0 ] || { echo 'Run the installer with sudo' >&2; exit 1; }
|
||||
case "$operator" in ''|*[!A-Za-z0-9_.-]*) echo 'Supply the desktop account using --user' >&2; exit 1;; esac
|
||||
uid=$(id -u "$operator")
|
||||
[ "$uid" != 0 ] || { echo 'Use a non-root desktop account' >&2; exit 1; }
|
||||
gid=$(id -g "$operator")
|
||||
base=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
platform=$(uname -s)
|
||||
version=$(cat "$base/architecture")
|
||||
case "$(uname -m):$version" in x86_64:x64|arm64:arm64|aarch64:arm64) ;; *) echo 'This package targets a different CPU' >&2; exit 1;; esac
|
||||
|
||||
case "$platform" in
|
||||
Linux)
|
||||
command -v systemctl >/dev/null
|
||||
home=$(getent passwd "$operator" | cut -d: -f6)
|
||||
root=/opt/lanups; data=/etc/LanUps; group=root
|
||||
test -f "$base/lanups-agent.service"
|
||||
;;
|
||||
Darwin)
|
||||
home=$(dscl . -read "/Users/$operator" NFSHomeDirectory | sed 's/^NFSHomeDirectory: //')
|
||||
root=/usr/local/libexec/lanups; data='/Library/Application Support/LanUps'; group=wheel
|
||||
test -f "$base/local.lanups.agent.plist"
|
||||
if [ -e /Applications/LanUps.app ] && [ ! -L /Applications/LanUps.app ]; then
|
||||
echo '/Applications/LanUps.app already exists and is not managed by this installer' >&2; exit 1
|
||||
fi
|
||||
;;
|
||||
*) echo 'This installer supports Linux with systemd and macOS' >&2; exit 1;;
|
||||
esac
|
||||
case "$home" in /*) ;; *) echo 'Cannot determine the desktop account home' >&2; exit 1;; esac
|
||||
|
||||
install -d -m 0755 -o root -g "$group" "$root" "$data"
|
||||
stage=$(mktemp -d "$root/release.XXXXXX")
|
||||
chmod 0755 "$stage"
|
||||
cp -R "$base/agent" "$stage/agent"
|
||||
chmod 0755 "$stage/agent/LanUps.Agent"
|
||||
if [ "$platform" = Linux ]; then
|
||||
cp -R "$base/desktop" "$stage/desktop"
|
||||
chmod 0755 "$stage/desktop/LanUps.Desktop"
|
||||
install -m 0644 "$base/ups.png" "$stage/ups.png"
|
||||
else
|
||||
cp -R "$base/LanUps.app" "$stage/LanUps.app"
|
||||
chmod 0755 "$stage/LanUps.app/Contents/MacOS/LanUps.Desktop"
|
||||
fi
|
||||
chown -R root:"$group" "$stage"
|
||||
chmod -R go-w "$stage"
|
||||
|
||||
token="$data/agent.token"
|
||||
if [ ! -f "$token" ]; then "$stage/agent/LanUps.Agent" --provision; fi
|
||||
chmod 0600 "$token"
|
||||
|
||||
if [ "$platform" = Linux ]; then
|
||||
getent group lanups-operators >/dev/null || groupadd --system lanups-operators
|
||||
usermod -a -G lanups-operators "$operator"
|
||||
chown root:lanups-operators "$token"
|
||||
chmod 0640 "$token"
|
||||
|
||||
args=''
|
||||
[ "$mode" = simulation ] || args=' --enable-shutdown'
|
||||
sed "s|^ExecStart=.*|ExecStart=$stage/agent/LanUps.Agent$args|" "$base/lanups-agent.service" >"$stage/lanups-agent.service"
|
||||
install -m 0644 "$stage/lanups-agent.service" /etc/systemd/system/lanups-agent.service
|
||||
install -d -m 0755 /usr/local/share/applications
|
||||
sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop|; /^Icon=/d; \$a Icon=$stage/ups.png" "$base/lanups-desktop.desktop" >"$stage/menu.desktop"
|
||||
install -m 0644 "$stage/menu.desktop" /usr/local/share/applications/lanups-desktop.desktop
|
||||
sed "s|^Exec=.*|Exec=$stage/desktop/LanUps.Desktop --tray|" "$base/lanups-desktop.desktop" >"$stage/autostart.desktop"
|
||||
sudo -u "$operator" mkdir -p "$home/.config/autostart"
|
||||
sudo -u "$operator" install -m 0644 "$stage/autostart.desktop" "$home/.config/autostart/lanups-desktop.desktop"
|
||||
systemctl daemon-reload
|
||||
systemctl enable lanups-agent.service
|
||||
systemctl restart lanups-agent.service
|
||||
else
|
||||
chmod -N "$token"
|
||||
chmod +a "user:$operator allow read" "$token"
|
||||
if launchctl print system/local.lanups.agent >/dev/null 2>&1; then launchctl bootout system/local.lanups.agent; fi
|
||||
suffix=''
|
||||
[ "$mode" = simulation ] || suffix='<string>--enable-shutdown</string>'
|
||||
sed "s|/usr/local/libexec/lanups/agent/LanUps.Agent</string>|$stage/agent/LanUps.Agent</string>$suffix|" \
|
||||
"$base/local.lanups.agent.plist" >"$stage/agent.plist"
|
||||
install -m 0644 -o root -g wheel "$stage/agent.plist" /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if launchctl print "gui/$uid/local.lanups.desktop" >/dev/null 2>&1; then launchctl bootout "gui/$uid/local.lanups.desktop"; fi
|
||||
app=/Applications/LanUps.app
|
||||
ln -sfn "$stage/LanUps.app" "$app"
|
||||
sudo -u "$operator" mkdir -p "$home/Library/LaunchAgents"
|
||||
sudo -u "$operator" install -m 0644 "$base/local.lanups.desktop.plist" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
launchctl bootstrap system /Library/LaunchDaemons/local.lanups.agent.plist
|
||||
if launchctl print "gui/$uid" >/dev/null 2>&1; then
|
||||
launchctl bootstrap "gui/$uid" "$home/Library/LaunchAgents/local.lanups.desktop.plist"
|
||||
fi
|
||||
fi
|
||||
echo "LAN UPS installed ($mode). The desktop client automatically starts at login."
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
setlocal
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Setup.ps1" %*
|
||||
if errorlevel 1 pause
|
||||
@@ -0,0 +1,57 @@
|
||||
param([string]$Operator = [Security.Principal.WindowsIdentity]::GetCurrent().Name, [switch]$EnableShutdown)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
if (!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
if ($Operator -match '["\r\n]') { throw 'Invalid operator account' }
|
||||
$arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -Operator "{1}"' -f $PSCommandPath, $Operator
|
||||
if ($EnableShutdown) { $arguments += ' -EnableShutdown' }
|
||||
$process = Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments -Wait -PassThru -WindowStyle Hidden
|
||||
exit $process.ExitCode
|
||||
}
|
||||
|
||||
$destination = Join-Path $env:ProgramFiles 'LanUps'
|
||||
$logDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
|
||||
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
|
||||
$log = Join-Path $logDirectory 'setup.log'
|
||||
Start-Transcript -Path $log -Append | Out-Null
|
||||
try {
|
||||
foreach ($kind in @('Agent', 'Desktop')) {
|
||||
if (!(Test-Path -LiteralPath (Join-Path $PSScriptRoot "$kind\LanUps.$kind.exe") -PathType Leaf)) {
|
||||
throw "Extract the entire installer archive before running Setup.cmd: missing $kind"
|
||||
}
|
||||
}
|
||||
$service = Get-Service 'LanUps.Agent' -ErrorAction SilentlyContinue
|
||||
if ($service -and $service.Status -ne 'Stopped') { Stop-Service $service }
|
||||
$task = Get-ScheduledTask -TaskName 'LanUps Desktop' -ErrorAction SilentlyContinue
|
||||
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask $task }
|
||||
$existingDesktop = Join-Path $destination 'Desktop\LanUps.Desktop.exe'
|
||||
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object Path -EQ $existingDesktop |
|
||||
ForEach-Object { Stop-Process -Id $_.Id; $_.WaitForExit() }
|
||||
|
||||
foreach ($kind in @('Agent', 'Desktop')) {
|
||||
$target = Join-Path $destination $kind
|
||||
New-Item -ItemType Directory -Path $target -Force | Out-Null
|
||||
Copy-Item -Path (Join-Path $PSScriptRoot "$kind\*") -Destination $target -Recurse -Force
|
||||
}
|
||||
& (Join-Path $PSScriptRoot 'install.ps1') -Operator $Operator -EnableShutdown:$EnableShutdown
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
$shortcut = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) '局域网 UPS.lnk'))
|
||||
$shortcut.TargetPath = $existingDesktop
|
||||
$shortcut.WorkingDirectory = (Split-Path -Parent $existingDesktop)
|
||||
$shortcut.IconLocation = "$existingDesktop,0"
|
||||
$shortcut.Save()
|
||||
if ($identity.Name -ieq $Operator) {
|
||||
$personalPath = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) '局域网 UPS.lnk'
|
||||
if (Test-Path -LiteralPath $personalPath) {
|
||||
$personal = $shell.CreateShortcut($personalPath)
|
||||
if ((Split-Path -Leaf $personal.TargetPath) -ieq 'LanUps.Desktop.exe') {
|
||||
$personal.TargetPath = $existingDesktop
|
||||
$personal.WorkingDirectory = (Split-Path -Parent $existingDesktop)
|
||||
$personal.IconLocation = "$existingDesktop,0"
|
||||
$personal.Save()
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Host "Installed: $destination"
|
||||
} finally { Stop-Transcript | Out-Null }
|
||||
@@ -0,0 +1,56 @@
|
||||
#Requires -RunAsAdministrator
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Operator,
|
||||
[switch]$EnableShutdown
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$appRoot = Join-Path $env:ProgramFiles 'LanUps'
|
||||
$agent = Join-Path $appRoot 'Agent\LanUps.Agent.exe'
|
||||
$desktop = Join-Path $appRoot 'Desktop\LanUps.Desktop.exe'
|
||||
foreach ($app in @($agent, $desktop)) {
|
||||
if (!(Test-Path -LiteralPath $app -PathType Leaf)) { throw "Missing $app" }
|
||||
}
|
||||
$operatorSid = ([Security.Principal.NTAccount]::new($Operator)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps'
|
||||
$token = Join-Path $data 'agent.token'
|
||||
New-Item -ItemType Directory -Path $data -Force | Out-Null
|
||||
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
||||
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
|
||||
$operatorId = [Security.Principal.SecurityIdentifier]::new($operatorSid)
|
||||
$directoryRules = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$directoryRules.SetAccessRuleProtection($true, $false)
|
||||
foreach ($principalId in @($system, $administrators)) {
|
||||
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
}
|
||||
$directoryRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'ReadAndExecute', 'Allow'))
|
||||
Set-Acl -LiteralPath $data -AclObject $directoryRules
|
||||
if (!(Test-Path -LiteralPath $token)) {
|
||||
& $agent --provision
|
||||
if ($LASTEXITCODE) { throw 'Unable to create local Agent credential' }
|
||||
}
|
||||
$tokenRules = [Security.AccessControl.FileSecurity]::new()
|
||||
$tokenRules.SetAccessRuleProtection($true, $false)
|
||||
foreach ($principalId in @($system, $administrators)) {
|
||||
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principalId, 'FullControl', 'Allow'))
|
||||
}
|
||||
$tokenRules.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($operatorId, 'Read', 'Allow'))
|
||||
Set-Acl -LiteralPath $token -AclObject $tokenRules
|
||||
|
||||
$command = '"' + $agent + '"'
|
||||
if ($EnableShutdown) { $command += ' --enable-shutdown' }
|
||||
$installed = Get-CimInstance Win32_Service -Filter "Name='LanUps.Agent'"
|
||||
if ($installed) {
|
||||
Stop-Service 'LanUps.Agent' -ErrorAction Stop
|
||||
$changed = Invoke-CimMethod -InputObject $installed -MethodName Change -Arguments @{PathName=$command;StartMode='Automatic'}
|
||||
if ($changed.ReturnValue) { throw "Cannot update Agent service: $($changed.ReturnValue)" }
|
||||
} else {
|
||||
New-Service -Name 'LanUps.Agent' -BinaryPathName $command -DisplayName 'LAN UPS Agent' -StartupType Automatic | Out-Null
|
||||
}
|
||||
Start-Service -Name 'LanUps.Agent'
|
||||
|
||||
$action = New-ScheduledTaskAction -Execute $desktop -Argument '--tray' -WorkingDirectory (Split-Path -Parent $desktop)
|
||||
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $Operator
|
||||
$principal = New-ScheduledTaskPrincipal -UserId $Operator -LogonType Interactive -RunLevel Limited
|
||||
Register-ScheduledTask -TaskName 'LanUps Desktop' -Action $action -Trigger $trigger -Principal $principal -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) -Force | Out-Null
|
||||
Start-ScheduledTask -TaskName 'LanUps Desktop'
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using LanUps.Core;
|
||||
|
||||
namespace LanUps.Agent;
|
||||
|
||||
internal sealed class Coordinator
|
||||
{
|
||||
private static readonly TimeSpan Countdown = TimeSpan.FromMinutes(1);
|
||||
private readonly object _gate = new();
|
||||
private readonly string _settingsPath;
|
||||
private readonly bool _dryRun;
|
||||
private readonly ILogger _log;
|
||||
private readonly CancellationToken _stopping;
|
||||
private readonly string _shutdownStatePath;
|
||||
private NutEndpoint _endpoint;
|
||||
private UpsUpdate _update = new(null, null, false);
|
||||
private ShutdownNotice? _pending;
|
||||
private string? _lastAction;
|
||||
private string? _previousStatus;
|
||||
private bool _signalLatched;
|
||||
private CancellationTokenSource? _monitor;
|
||||
|
||||
public Coordinator(string settingsPath, bool dryRun, ILogger log, CancellationToken stopping)
|
||||
{
|
||||
_settingsPath = settingsPath;
|
||||
_shutdownStatePath = Path.ChangeExtension(settingsPath, dryRun ? ".simulation.json" : ".shutdown.json");
|
||||
_dryRun = dryRun;
|
||||
_log = log;
|
||||
_stopping = stopping;
|
||||
_endpoint = LoadEndpoint();
|
||||
if (File.Exists(_shutdownStatePath))
|
||||
{
|
||||
var saved = JsonSerializer.Deserialize(File.ReadAllText(_shutdownStatePath), ShutdownJson.Default.ShutdownState);
|
||||
if (saved?.Endpoint == _endpoint)
|
||||
{
|
||||
_pending = saved.Pending;
|
||||
_signalLatched = saved.SignalLatched;
|
||||
_lastAction = saved.LastAction;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_pending is { } pending) _ = WaitForDeadlineAsync(pending);
|
||||
StartMonitor();
|
||||
}
|
||||
}
|
||||
|
||||
public AgentState Snapshot()
|
||||
{
|
||||
lock (_gate) return new(_endpoint, _update, _pending, _lastAction, _dryRun);
|
||||
}
|
||||
|
||||
public bool SetEndpoint(NutEndpoint endpoint)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (endpoint == _endpoint) return true;
|
||||
if (_pending is not null) return false;
|
||||
WriteJson(_settingsPath, endpoint, AgentJson.Default.NutEndpoint);
|
||||
_endpoint = endpoint;
|
||||
_update = new(null, null, false);
|
||||
_signalLatched = false;
|
||||
_previousStatus = null;
|
||||
_lastAction = null;
|
||||
StartMonitor();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Respond(Guid id, bool confirm) => Finish(id, confirm ? "用户确认" : "用户取消", confirm);
|
||||
|
||||
private NutEndpoint LoadEndpoint()
|
||||
{
|
||||
if (!File.Exists(_settingsPath)) return NutEndpoint.Default;
|
||||
var saved = JsonSerializer.Deserialize(File.ReadAllText(_settingsPath), AgentJson.Default.NutEndpoint);
|
||||
if (saved is not null && NutEndpoint.TryParse(saved.Host, saved.Port.ToString(), saved.Name, out var endpoint)) return endpoint;
|
||||
throw new InvalidDataException("Invalid saved NUT endpoint");
|
||||
}
|
||||
|
||||
private void StartMonitor()
|
||||
{
|
||||
_monitor?.Cancel();
|
||||
var monitor = CancellationTokenSource.CreateLinkedTokenSource(_stopping);
|
||||
_monitor = monitor;
|
||||
var endpoint = _endpoint;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try { await NutMonitor.RunAsync(endpoint, update => Observe(monitor, update), monitor.Token); }
|
||||
catch (OperationCanceledException) when (monitor.IsCancellationRequested) { }
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_monitor == monitor) _monitor = null;
|
||||
monitor.Dispose();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void Observe(CancellationTokenSource monitor, UpsUpdate update)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_monitor != monitor || monitor.IsCancellationRequested) return;
|
||||
_update = update;
|
||||
var status = update.Error is { } error ? $"通讯中断 {error}" : $"UPS 状态 {update.LastReading?.Get("ups.status")}";
|
||||
if (status != _previousStatus) _log.LogInformation("{Status}", status);
|
||||
_previousStatus = status;
|
||||
if (update.Error is not null || update.LastReading is not { } reading) return;
|
||||
|
||||
var hasSignal = reading.Has("FSD");
|
||||
if (!hasSignal)
|
||||
{
|
||||
if (_signalLatched) { _signalLatched = false; SaveShutdownState(); }
|
||||
return;
|
||||
}
|
||||
if (_signalLatched) return;
|
||||
_signalLatched = true;
|
||||
if (_pending is not null) { SaveShutdownState(); return; }
|
||||
var pending = new ShutdownNotice(Guid.NewGuid(), DateTimeOffset.UtcNow + Countdown);
|
||||
_pending = pending;
|
||||
_lastAction = null;
|
||||
SaveShutdownState();
|
||||
_log.LogWarning("收到 FSD,关机倒计时至 {Deadline}", pending.Deadline);
|
||||
_ = WaitForDeadlineAsync(pending);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WaitForDeadlineAsync(ShutdownNotice pending)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (pending.Deadline - DateTimeOffset.UtcNow is { } remaining && remaining > TimeSpan.Zero)
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(Math.Ceiling(remaining.TotalMilliseconds)), _stopping);
|
||||
if (!_stopping.IsCancellationRequested) Finish(pending.Id, "60 秒内无响应", true);
|
||||
}
|
||||
catch (OperationCanceledException) when (_stopping.IsCancellationRequested) { }
|
||||
}
|
||||
|
||||
private bool Finish(Guid id, string reason, bool shutdown)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_pending?.Id != id) return false;
|
||||
_pending = null;
|
||||
_lastAction = shutdown ? $"{reason} · {(_dryRun ? "已模拟关机" : "已提交关机")}" : reason;
|
||||
SaveShutdownState();
|
||||
_log.LogWarning("{Result}", _lastAction);
|
||||
if (shutdown && !_dryRun) _ = Task.Run(ExecuteShutdownAsync);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExecuteShutdownAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var executable = OperatingSystem.IsWindows() ? Path.Combine(Environment.SystemDirectory, "shutdown.exe") :
|
||||
OperatingSystem.IsMacOS() ? "/sbin/shutdown" : "/usr/bin/systemctl";
|
||||
var arguments = OperatingSystem.IsWindows() ? "/s /t 0" : OperatingSystem.IsMacOS() ? "-h now" : "poweroff";
|
||||
using var process = Process.Start(new ProcessStartInfo(executable, arguments) { UseShellExecute = false });
|
||||
if (process is null) throw new IOException("未能启动系统关机程序");
|
||||
await process.WaitForExitAsync();
|
||||
if (process.ExitCode != 0) throw new IOException($"关机程序退出码 {process.ExitCode}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lastAction = $"关机执行失败:{ex.Message}";
|
||||
SaveShutdownState();
|
||||
_log.LogError(ex, "关机执行失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveShutdownState()
|
||||
{
|
||||
try { WriteJson(_shutdownStatePath, new ShutdownState(_endpoint, _pending, _signalLatched, _lastAction), ShutdownJson.Default.ShutdownState); }
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { _log.LogError(ex, "保存关机状态失败"); }
|
||||
}
|
||||
|
||||
private static void WriteJson<T>(string path, T value, JsonTypeInfo<T> type)
|
||||
{
|
||||
var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||
try { File.WriteAllText(temp, JsonSerializer.Serialize(value, type)); File.Move(temp, path, overwrite: true); }
|
||||
finally { if (File.Exists(temp)) File.Delete(temp); }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal sealed record ShutdownState(NutEndpoint Endpoint, ShutdownNotice? Pending, bool SignalLatched, string? LastAction);
|
||||
|
||||
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
|
||||
[JsonSerializable(typeof(ShutdownState))]
|
||||
internal sealed partial class ShutdownJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
<PropertyGroup Condition="'$(PublishAot)' == 'true' Or '$(PublishTrimmed)' == 'true'">
|
||||
<EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../LanUps.Core/LanUps.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(PublishTrimmed)' == 'true' And '$(PublishAot)' != 'true'">
|
||||
<TrimmerRootDescriptor Include="LinkerRoots.xml" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,7 @@
|
||||
<linker>
|
||||
<!-- Kestrel's configuration loader can load these collection types even on an HTTP-only endpoint. -->
|
||||
<assembly fullname="System.Security.Cryptography">
|
||||
<type fullname="System.Security.Cryptography.X509Certificates.X509CertificateCollection" preserve="all" />
|
||||
<type fullname="System.Security.Cryptography.X509Certificates.X509Certificate2Collection" preserve="all" />
|
||||
</assembly>
|
||||
</linker>
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.Security.Cryptography;
|
||||
using LanUps.Agent;
|
||||
using LanUps.Core;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
if (args is ["--provision"])
|
||||
{
|
||||
var path = AgentLocation.TokenPath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
using var writer = new StreamWriter(file);
|
||||
writer.Write(Convert.ToHexString(RandomNumberGenerator.GetBytes(32)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.Length > 0 && args is not ["--enable-shutdown"])
|
||||
throw new ArgumentException("Usage: LanUps.Agent [--provision | --enable-shutdown]");
|
||||
|
||||
var token = Convert.FromHexString(File.ReadAllText(AgentLocation.TokenPath).Trim());
|
||||
if (token.Length != 32) throw new InvalidDataException("Agent token must contain 32 bytes");
|
||||
|
||||
var options = new WebApplicationOptions { Args = [], ContentRootPath = AppContext.BaseDirectory };
|
||||
var builder = WebApplication.CreateSlimBuilder(options);
|
||||
builder.Services.ConfigureHttpJsonOptions(json => json.SerializerOptions.TypeInfoResolverChain.Insert(0, AgentJson.Default));
|
||||
builder.Services.AddWindowsService(service => service.ServiceName = "LanUps.Agent");
|
||||
builder.WebHost.ConfigureKestrel(server =>
|
||||
{
|
||||
server.Listen(System.Net.IPAddress.Loopback, AgentLocation.Port);
|
||||
server.Limits.MaxRequestBodySize = 4096;
|
||||
});
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
|
||||
var app = builder.Build();
|
||||
var agent = new Coordinator(Path.ChangeExtension(AgentLocation.TokenPath, ".json"), args.Length == 0, app.Logger, app.Lifetime.ApplicationStopping);
|
||||
app.Lifetime.ApplicationStarted.Register(agent.Start);
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
byte[]? supplied = null;
|
||||
var candidate = context.Request.Headers["X-LanUps-Token"].ToString();
|
||||
if (candidate.Length == 64)
|
||||
{
|
||||
try { supplied = Convert.FromHexString(candidate); }
|
||||
catch (FormatException) { }
|
||||
}
|
||||
if (supplied is null || !CryptographicOperations.FixedTimeEquals(token, supplied))
|
||||
{
|
||||
context.Response.StatusCode = 401;
|
||||
await context.Response.WriteAsync("后台服务认证失败");
|
||||
return;
|
||||
}
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
await next();
|
||||
});
|
||||
|
||||
app.MapGet("/status", () => agent.Snapshot());
|
||||
app.MapPut("/endpoint", ([FromBody] NutEndpoint proposed) =>
|
||||
{
|
||||
if (!NutEndpoint.TryParse(proposed.Host, proposed.Port.ToString(), proposed.Name, out var endpoint))
|
||||
return Results.BadRequest("请输入有效的 NUT 配置");
|
||||
try { return agent.SetEndpoint(endpoint) ? Results.Ok(endpoint) : Results.Conflict("关机倒计时正在执行"); }
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return Results.Text("保存后台配置失败", statusCode: 500); }
|
||||
});
|
||||
app.MapGet("/ups", async (string host, int port, CancellationToken cancellation) =>
|
||||
{
|
||||
if (!NutEndpoint.TryServer(host, port.ToString(), out var address, out _)) return Results.BadRequest("无效的服务器地址或端口");
|
||||
try
|
||||
{
|
||||
var names = await NutMonitor.DiscoverAsync(address, port, cancellation);
|
||||
return Results.Json(names.ToArray(), AgentJson.Default.StringArray);
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Net.Sockets.SocketException or IOException or OperationCanceledException)
|
||||
{ return Results.Text(ex is OperationCanceledException ? "NUT 查询超时" : ex.Message, statusCode: 502); }
|
||||
});
|
||||
app.MapPost("/shutdown/{id:guid}/{decision}", (Guid id, string decision) => decision is "confirm" or "cancel" && agent.Respond(id, decision == "confirm")
|
||||
? Results.Ok(decision) : Results.Conflict("关机请求已处理或不存在"));
|
||||
await app.RunAsync();
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
|
||||
namespace LanUps.Core;
|
||||
|
||||
public sealed record ShutdownNotice(Guid Id, DateTimeOffset Deadline);
|
||||
public sealed record AgentState(NutEndpoint Endpoint, UpsUpdate Update, ShutdownNotice? Pending, string? LastAction, bool DryRun);
|
||||
|
||||
public static class AgentLocation
|
||||
{
|
||||
public static int Port => int.TryParse(Environment.GetEnvironmentVariable("LANUPS_AGENT_PORT"), out var port) && port is > 0 and <= 65535 ? port : 47183;
|
||||
public static string TokenPath => Environment.GetEnvironmentVariable("LANUPS_AGENT_TOKEN") ?? Path.Combine(
|
||||
OperatingSystem.IsWindows() ? Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) :
|
||||
OperatingSystem.IsMacOS() ? "/Library/Application Support" : "/etc", "LanUps", "agent.token");
|
||||
}
|
||||
|
||||
public sealed class AgentClient : IDisposable
|
||||
{
|
||||
private readonly HttpClient _http = new(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false })
|
||||
{
|
||||
BaseAddress = new Uri($"http://127.0.0.1:{AgentLocation.Port}/"), Timeout = TimeSpan.FromSeconds(5)
|
||||
};
|
||||
|
||||
public Task<AgentState> StatusAsync(CancellationToken token) => SendAsync(HttpMethod.Get, "status", null, AgentJson.Default.AgentState, token);
|
||||
public Task<NutEndpoint> SaveAsync(NutEndpoint endpoint, CancellationToken token) =>
|
||||
SendAsync(HttpMethod.Put, "endpoint", JsonContent.Create(endpoint, AgentJson.Default.NutEndpoint), AgentJson.Default.NutEndpoint, token);
|
||||
public Task<string[]> DiscoverAsync(string host, int port, CancellationToken token) =>
|
||||
SendAsync(HttpMethod.Get, $"ups?host={Uri.EscapeDataString(host)}&port={port}", null, AgentJson.Default.StringArray, token);
|
||||
public Task<string> RespondAsync(Guid id, bool confirm, CancellationToken token) =>
|
||||
SendAsync(HttpMethod.Post, $"shutdown/{id}/{(confirm ? "confirm" : "cancel")}", null, AgentJson.Default.String, token);
|
||||
|
||||
private async Task<T> SendAsync<T>(HttpMethod method, string path, HttpContent? content, JsonTypeInfo<T> type, CancellationToken cancellation)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path) { Content = content };
|
||||
request.Headers.TryAddWithoutValidation("X-LanUps-Token", (await File.ReadAllTextAsync(AgentLocation.TokenPath, cancellation)).Trim());
|
||||
using var response = await _http.SendAsync(request, cancellation);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new IOException(await response.Content.ReadAsStringAsync(cancellation));
|
||||
return await response.Content.ReadFromJsonAsync(type, cancellation) ?? throw new IOException("后台服务未返回数据");
|
||||
}
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace LanUps.Core;
|
||||
|
||||
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
|
||||
[JsonSerializable(typeof(AgentState))]
|
||||
[JsonSerializable(typeof(NutEndpoint))]
|
||||
[JsonSerializable(typeof(string[]))]
|
||||
[JsonSerializable(typeof(string))]
|
||||
public sealed partial class AgentJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,3 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace LanUps.Core;
|
||||
|
||||
public sealed record NutEndpoint(string Host, int Port, string Name)
|
||||
{
|
||||
public static NutEndpoint Default { get; } = new("192.168.5.1", 3493, "h1000m");
|
||||
|
||||
public static bool TryParse(string? host, string? port, string? name, out NutEndpoint endpoint)
|
||||
{
|
||||
host = host?.Trim();
|
||||
name = name?.Trim();
|
||||
if (TryServer(host, port, out var server, out var number) &&
|
||||
name is not null && Regex.IsMatch(name, @"\A[A-Za-z0-9_.-]{1,128}\z"))
|
||||
{
|
||||
endpoint = new(server, number, name);
|
||||
return true;
|
||||
}
|
||||
endpoint = Default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryServer(string? host, string? port, out string server, out int number)
|
||||
{
|
||||
server = (host ?? "").Trim();
|
||||
return int.TryParse(port, out number) && number is > 0 and <= 65535 &&
|
||||
Uri.CheckHostName(server) != UriHostNameType.Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record UpsReading(DateTimeOffset At, IReadOnlyDictionary<string, string> Values)
|
||||
{
|
||||
public string? Get(string key) => Values.GetValueOrDefault(key);
|
||||
public bool Has(string flag) => (Get("ups.status") ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(flag, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public sealed record UpsUpdate(UpsReading? LastReading, string? Error, bool NewShutdownSignal);
|
||||
|
||||
public static class NutMonitor
|
||||
{
|
||||
public static async Task RunAsync(NutEndpoint endpoint, Action<UpsUpdate> publish, CancellationToken cancellation)
|
||||
{
|
||||
UpsReading? lastReading = null;
|
||||
var shutdownSignalSeen = false;
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
string? error = null;
|
||||
var newSignal = false;
|
||||
try
|
||||
{
|
||||
lastReading = await ReadAsync(endpoint, cancellation).ConfigureAwait(false);
|
||||
var hasSignal = lastReading.Has("FSD");
|
||||
newSignal = hasSignal && !shutdownSignalSeen;
|
||||
shutdownSignalSeen = hasSignal;
|
||||
}
|
||||
catch (Exception ex) when (ex is SocketException or IOException or OperationCanceledException)
|
||||
{
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
error = ex is OperationCanceledException ? "连接或读取超时" : ex.Message;
|
||||
}
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
publish(new(lastReading, error, newSignal));
|
||||
await Task.Delay(TimeSpan.FromSeconds(3), cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<IReadOnlyList<string>> DiscoverAsync(string host, int port, CancellationToken cancellation)
|
||||
{
|
||||
var rows = await ListAsync(host, port, "LIST UPS", cancellation).ConfigureAwait(false);
|
||||
var names = new List<string>();
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var parts = row.Split(' ', 3);
|
||||
if (parts.Length != 3 || parts[0] != "UPS")
|
||||
throw new IOException("NUT 返回了格式错误的 UPS 名称");
|
||||
if (Regex.IsMatch(parts[1], @"\A[A-Za-z0-9_.-]{1,128}\z"))
|
||||
names.Add(parts[1]);
|
||||
}
|
||||
return names.Distinct(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
private static async Task<UpsReading> ReadAsync(NutEndpoint endpoint, CancellationToken cancellation)
|
||||
{
|
||||
var rows = await ListAsync(endpoint.Host, endpoint.Port, $"LIST VAR {endpoint.Name}", cancellation).ConfigureAwait(false);
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
var prefix = $"VAR {endpoint.Name} ";
|
||||
foreach (var line in rows)
|
||||
{
|
||||
if (!line.StartsWith(prefix, StringComparison.Ordinal))
|
||||
throw new IOException("NUT 返回了格式错误的变量");
|
||||
var separator = line.IndexOf(' ', prefix.Length);
|
||||
if (separator <= prefix.Length || separator + 2 >= line.Length || line[separator + 1] != '"' || line[^1] != '"')
|
||||
throw new IOException("NUT 返回了格式错误的变量");
|
||||
values[line[prefix.Length..separator]] = Regex.Replace(line[(separator + 2)..^1], "\\\\([\\\\\"])", "$1");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(values.GetValueOrDefault("ups.status")))
|
||||
throw new IOException("NUT 未返回供电状态");
|
||||
return new(DateTimeOffset.Now, values);
|
||||
}
|
||||
|
||||
private static async Task<List<string>> ListAsync(string host, int port, string request, CancellationToken cancellation)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
var token = timeout.Token;
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(host, port, token).ConfigureAwait(false);
|
||||
using var stream = client.GetStream();
|
||||
await stream.WriteAsync(Encoding.ASCII.GetBytes(request + "\n"), token).ConfigureAwait(false);
|
||||
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var header = await reader.ReadLineAsync(token).ConfigureAwait(false);
|
||||
if (header != $"BEGIN {request}")
|
||||
throw new IOException(header ?? "NUT 服务端关闭了连接");
|
||||
|
||||
var rows = new List<string>();
|
||||
for (var row = 0; row < 512; row++)
|
||||
{
|
||||
var line = await reader.ReadLineAsync(token).ConfigureAwait(false);
|
||||
if (line == $"END {request}")
|
||||
return rows;
|
||||
if (line is null || line.StartsWith("ERR ", StringComparison.Ordinal))
|
||||
throw new IOException(line?.StartsWith("ERR ", StringComparison.Ordinal) == true ? line : "NUT 返回了不完整的读数");
|
||||
rows.Add(line);
|
||||
}
|
||||
throw new IOException("NUT 响应超出监控范围");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Application xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:semi="https://irihi.tech/semi" x:Class="LanUps.Desktop.App" RequestedThemeVariant="Default">
|
||||
<Application.Styles>
|
||||
<semi:SemiTheme Locale="zh-CN" />
|
||||
</Application.Styles>
|
||||
<TrayIcon.Icons>
|
||||
<TrayIcons>
|
||||
<TrayIcon Icon="avares://LanUps.Desktop/Assets/ups.ico" ToolTipText="局域网 UPS" Clicked="ShowDashboard">
|
||||
<TrayIcon.Menu>
|
||||
<NativeMenu>
|
||||
<NativeMenuItem Header="显示监控" Click="ShowDashboard" />
|
||||
<NativeMenuItemSeparator />
|
||||
<NativeMenuItem Header="退出桌面端" Click="ExitDesktop" />
|
||||
</NativeMenu>
|
||||
</TrayIcon.Menu>
|
||||
</TrayIcon>
|
||||
</TrayIcons>
|
||||
</TrayIcon.Icons>
|
||||
</Application>
|
||||
@@ -0,0 +1,29 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
public sealed partial class App : Application
|
||||
{
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.MainWindow = new MainWindow(desktop.Args?.Contains("--tray", StringComparer.Ordinal) == true);
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
private void ShowDashboard(object? sender, EventArgs args)
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: MainWindow window })
|
||||
window.Restore();
|
||||
}
|
||||
|
||||
private void ExitDesktop(object? sender, EventArgs args)
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,15 @@
|
||||
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="LanUps.Desktop.CloseDialog" Title="关闭局域网 UPS" Width="400" SizeToContent="Height"
|
||||
CanResize="False" ShowInTaskbar="False" WindowStartupLocation="CenterOwner">
|
||||
<StackPanel Margin="24" Spacing="12">
|
||||
<TextBlock Text="关闭窗口时要执行什么操作?" FontSize="18" FontWeight="SemiBold" />
|
||||
<RadioButton x:Name="MinimizeOption" GroupName="CloseAction" Content="最小化,继续监控" IsChecked="True" />
|
||||
<RadioButton GroupName="CloseAction" Content="关闭桌面端" />
|
||||
<CheckBox x:Name="RememberOption" Content="记住此操作" />
|
||||
<TextBlock x:Name="SaveError" Text="无法保存偏好,可取消勾选后继续。" TextWrapping="Wrap" IsVisible="False" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="取消" IsCancel="True" Click="Cancel" />
|
||||
<Button Content="确定" IsDefault="True" Click="Confirm" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,34 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
public sealed partial class CloseDialog : Window
|
||||
{
|
||||
private readonly DesktopOptions _options;
|
||||
|
||||
public CloseDialog() : this(DesktopSettings.Load()) { }
|
||||
|
||||
internal CloseDialog(DesktopOptions options)
|
||||
{
|
||||
_options = options;
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void Cancel(object? sender, RoutedEventArgs args) => Close(null);
|
||||
|
||||
private void Confirm(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
var choice = MinimizeOption.IsChecked == true ? CloseAction.Minimize : CloseAction.Exit;
|
||||
if (RememberOption.IsChecked == true)
|
||||
{
|
||||
try { DesktopSettings.Save(_options with { CloseAction = choice }); }
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
SaveError.IsVisible = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
Close(choice);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using LanUps.Core;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
internal enum CloseAction { Minimize, Exit }
|
||||
|
||||
internal sealed record DesktopOptions(NutEndpoint Endpoint, CloseAction? CloseAction);
|
||||
|
||||
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
|
||||
[JsonSerializable(typeof(DesktopOptions))]
|
||||
internal sealed partial class DesktopJson : JsonSerializerContext;
|
||||
|
||||
internal static class DesktopSettings
|
||||
{
|
||||
private static readonly string DirectoryPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LanUps");
|
||||
private static readonly string SettingsPath = Path.Combine(DirectoryPath, "settings.json");
|
||||
public static string LogPath { get; } = Path.Combine(DirectoryPath, "desktop.log");
|
||||
|
||||
public static DesktopOptions Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(SettingsPath))
|
||||
{
|
||||
var saved = JsonSerializer.Deserialize(File.ReadAllText(SettingsPath), DesktopJson.Default.DesktopOptions);
|
||||
if (saved?.Endpoint is { } endpoint && NutEndpoint.TryParse(endpoint.Host, endpoint.Port.ToString(), endpoint.Name, out _) &&
|
||||
(saved.CloseAction is null || Enum.IsDefined(saved.CloseAction.Value)))
|
||||
return saved;
|
||||
}
|
||||
|
||||
var legacyAction = File.ReadAllText(Path.Combine(DirectoryPath, "close-action")) switch
|
||||
{
|
||||
"minimize" => CloseAction.Minimize,
|
||||
"exit" => CloseAction.Exit,
|
||||
_ => (CloseAction?)null
|
||||
};
|
||||
return new(NutEndpoint.Default, legacyAction);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
return new(NutEndpoint.Default, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Save(DesktopOptions options)
|
||||
{
|
||||
Directory.CreateDirectory(DirectoryPath);
|
||||
var temporary = SettingsPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||
try
|
||||
{
|
||||
File.WriteAllText(temporary, JsonSerializer.Serialize(options, DesktopJson.Default.DesktopOptions));
|
||||
File.Move(temporary, SettingsPath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporary)) File.Delete(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Log(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(DirectoryPath);
|
||||
if (File.Exists(LogPath) && new FileInfo(LogPath).Length >= 1024 * 1024)
|
||||
File.Move(LogPath, LogPath + ".1", overwrite: true);
|
||||
File.AppendAllText(LogPath, $"{DateTimeOffset.Now:O} {message.Replace('\r', ' ').Replace('\n', ' ')}{Environment.NewLine}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>WinExe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><ApplicationIcon>Assets/ups.ico</ApplicationIcon></PropertyGroup>
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets/ups.png;Assets/ups.ico" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="12.1.0" />
|
||||
<PackageReference Include="Semi.Avalonia" Version="12.1.0.2" />
|
||||
<ProjectReference Include="../LanUps.Core/LanUps.Core.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(PublishAot)' == 'true' And '$(LanUpsLinuxLibm)' != ''">
|
||||
<!-- Optional older glibc libm used only to set the Linux link-time ABI baseline. -->
|
||||
<NativeLibrary Include="$(LanUpsLinuxLibm)" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,83 @@
|
||||
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="LanUps.Desktop.MainWindow" Title="局域网 UPS" Icon="avares://LanUps.Desktop/Assets/ups.png"
|
||||
Width="760" Height="540" CanResize="False" WindowStartupLocation="CenterScreen">
|
||||
<Window.Styles>
|
||||
<Style Selector="Border.panel">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource SemiColorBorder}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="8" />
|
||||
<Setter Property="Padding" Value="20" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.metric">
|
||||
<Setter Property="FontSize" Value="26" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
</Style>
|
||||
<Style Selector="TextBlock.secondary"><Setter Property="Opacity" Value="0.72" /></Style>
|
||||
</Window.Styles>
|
||||
<Grid Margin="24">
|
||||
<StackPanel x:Name="DashboardPage" Spacing="14">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Content="设置" Click="OpenSettings" />
|
||||
<TextBlock Text="局域网 UPS" FontSize="31" FontWeight="SemiBold" />
|
||||
</DockPanel>
|
||||
<TextBlock x:Name="CurrentEndpoint" Classes="secondary" TextTrimming="CharacterEllipsis" />
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock x:Name="Supply" Text="正在连接" FontSize="24" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="Updated" Classes="secondary" Text="等待首次读数" />
|
||||
<TextBlock x:Name="ConnectionError" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" MaxLines="2"
|
||||
ToolTip.Tip="{Binding Text, RelativeSource={RelativeSource Self}}" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Grid ColumnDefinitions="*,*,*,*" ColumnSpacing="12">
|
||||
<Border Classes="panel"><StackPanel Spacing="6"><TextBlock Classes="secondary" Text="电池电量" /><TextBlock x:Name="Charge" Classes="metric" Text="—" /></StackPanel></Border>
|
||||
<Border Grid.Column="1" Classes="panel"><StackPanel Spacing="6"><TextBlock Classes="secondary" Text="负载" /><TextBlock x:Name="Load" Classes="metric" Text="—" /></StackPanel></Border>
|
||||
<Border Grid.Column="2" Classes="panel"><StackPanel Spacing="6"><TextBlock Classes="secondary" Text="输入电压" /><TextBlock x:Name="InputVoltage" Classes="metric" Text="—" /></StackPanel></Border>
|
||||
<Border Grid.Column="3" Classes="panel"><StackPanel Spacing="6"><TextBlock Classes="secondary" Text="输出电压" /><TextBlock x:Name="OutputVoltage" Classes="metric" Text="—" /></StackPanel></Border>
|
||||
</Grid>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock x:Name="ShutdownModeLabel" Text="关机信号" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="ShutdownSignal" Text="尚未收到关机信号" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<StackPanel x:Name="SettingsPage" IsVisible="False" Spacing="12">
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Right" Click="BackToDashboard" Content="返回主页" />
|
||||
<TextBlock Text="设置" FontSize="31" FontWeight="SemiBold" />
|
||||
</DockPanel>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="8">
|
||||
<Grid ColumnDefinitions="2*,*,2*,Auto" RowDefinitions="Auto,Auto" ColumnSpacing="12" RowSpacing="6">
|
||||
<TextBlock Text="NUT 服务器" /><TextBlock Grid.Column="1" Text="端口" /><TextBlock Grid.Column="2" Text="UPS 名称" />
|
||||
<TextBox Grid.Row="1" x:Name="HostBox" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" x:Name="PortBox" MaxLength="5" />
|
||||
<TextBox Grid.Row="1" Grid.Column="2" x:Name="NameBox" MaxLength="128" />
|
||||
<Button Grid.Row="1" Grid.Column="3" x:Name="RefreshUpsButton" Click="RefreshUps" Content="更新" VerticalAlignment="Stretch" />
|
||||
</Grid>
|
||||
<ComboBox x:Name="DiscoveredUps" PlaceholderText="选择发现的 UPS" SelectionChanged="SelectDiscoveredUps" IsVisible="False" />
|
||||
<TextBlock x:Name="SettingsStatus" TextWrapping="Wrap" MaxLines="2" TextTrimming="CharacterEllipsis" IsVisible="False" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="关闭窗口时" FontWeight="SemiBold" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="14">
|
||||
<RadioButton x:Name="AskOnClose" GroupName="CloseBehavior" Content="每次询问" />
|
||||
<RadioButton x:Name="MinimizeOnClose" GroupName="CloseBehavior" Content="最小化,继续监控" />
|
||||
<RadioButton x:Name="ExitOnClose" GroupName="CloseBehavior" Content="退出桌面端" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="panel">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Text="日志文件" FontWeight="SemiBold" />
|
||||
<SelectableTextBlock x:Name="LogLocation" TextWrapping="Wrap" />
|
||||
<TextBlock x:Name="LogWarning" IsVisible="False" Text="日志写入失败,请检查设置目录的权限。" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Button Click="SaveSettings" Content="保存" HorizontalAlignment="Right" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,306 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using LanUps.Core;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
public sealed partial class MainWindow : Window
|
||||
{
|
||||
private readonly AgentClient _agent = new();
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private CancellationTokenSource? _discovery;
|
||||
private DesktopOptions _options = DesktopSettings.Load();
|
||||
private AgentState? _agentState;
|
||||
private ShutdownDialog? _shutdownDialog;
|
||||
private bool _savingSettings;
|
||||
private string? _previousStatus;
|
||||
private bool _logFailed;
|
||||
private bool _closeDialogOpen;
|
||||
private bool _exitConfirmed;
|
||||
private readonly bool _startMinimized;
|
||||
|
||||
public MainWindow() : this(false) { }
|
||||
|
||||
internal MainWindow(bool startMinimized)
|
||||
{
|
||||
_startMinimized = startMinimized;
|
||||
InitializeComponent();
|
||||
LogLocation.Text = DesktopSettings.LogPath;
|
||||
Closing += ConfirmClose;
|
||||
Opened += StartMonitoring;
|
||||
Closed += (_, _) =>
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
_discovery?.Cancel();
|
||||
_agent.Dispose();
|
||||
WriteLog("桌面端退出");
|
||||
};
|
||||
}
|
||||
|
||||
private void StartMonitoring(object? sender, EventArgs args)
|
||||
{
|
||||
Opened -= StartMonitoring;
|
||||
if (_startMinimized) Minimize();
|
||||
_ = ObserveAgentAsync();
|
||||
}
|
||||
|
||||
internal void Restore()
|
||||
{
|
||||
if (!IsVisible)
|
||||
Show();
|
||||
WindowState = WindowState.Normal;
|
||||
if (OwnedWindows.FirstOrDefault(window => window.IsVisible) is { } dialog)
|
||||
dialog.Activate();
|
||||
else
|
||||
Activate();
|
||||
}
|
||||
|
||||
private void Minimize()
|
||||
{
|
||||
// Linux desktops may lack a tray host. Keep their taskbar entry reachable.
|
||||
if (OperatingSystem.IsLinux())
|
||||
WindowState = WindowState.Minimized;
|
||||
else
|
||||
Hide();
|
||||
}
|
||||
|
||||
private async void ConfirmClose(object? sender, WindowClosingEventArgs args)
|
||||
{
|
||||
if (_exitConfirmed || args.CloseReason is WindowCloseReason.OSShutdown or WindowCloseReason.ApplicationShutdown ||
|
||||
_options.CloseAction == CloseAction.Exit)
|
||||
return;
|
||||
|
||||
args.Cancel = true;
|
||||
if (_closeDialogOpen)
|
||||
return;
|
||||
|
||||
if (_options.CloseAction == CloseAction.Minimize)
|
||||
{
|
||||
Minimize();
|
||||
return;
|
||||
}
|
||||
|
||||
_closeDialogOpen = true;
|
||||
CloseAction? choice;
|
||||
try
|
||||
{
|
||||
choice = await new CloseDialog(_options).ShowDialog<CloseAction?>(this);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_closeDialogOpen = false;
|
||||
}
|
||||
|
||||
_options = DesktopSettings.Load();
|
||||
if (choice == CloseAction.Minimize)
|
||||
Minimize();
|
||||
else if (choice == CloseAction.Exit)
|
||||
{
|
||||
_exitConfirmed = true;
|
||||
Close();
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenSettings(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
var endpoint = _agentState?.Endpoint ?? _options.Endpoint;
|
||||
HostBox.Text = endpoint.Host;
|
||||
PortBox.Text = endpoint.Port.ToString();
|
||||
NameBox.Text = endpoint.Name;
|
||||
AskOnClose.IsChecked = _options.CloseAction is null;
|
||||
MinimizeOnClose.IsChecked = _options.CloseAction == CloseAction.Minimize;
|
||||
ExitOnClose.IsChecked = _options.CloseAction == CloseAction.Exit;
|
||||
SettingsStatus.IsVisible = false;
|
||||
DiscoveredUps.IsVisible = false;
|
||||
LogWarning.IsVisible = _logFailed;
|
||||
DashboardPage.IsVisible = false;
|
||||
SettingsPage.IsVisible = true;
|
||||
}
|
||||
|
||||
private void BackToDashboard(object? sender, RoutedEventArgs args) => ShowDashboard();
|
||||
|
||||
private void ShowDashboard()
|
||||
{
|
||||
_discovery?.Cancel();
|
||||
SettingsPage.IsVisible = false;
|
||||
DashboardPage.IsVisible = true;
|
||||
}
|
||||
|
||||
private async void SaveSettings(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
if (_savingSettings) return;
|
||||
if (!NutEndpoint.TryParse(HostBox.Text, PortBox.Text, NameBox.Text, out var endpoint))
|
||||
{
|
||||
SettingsMessage("请输入有效的服务器地址、端口和 UPS 名称。");
|
||||
return;
|
||||
}
|
||||
var close = MinimizeOnClose.IsChecked == true ? CloseAction.Minimize :
|
||||
ExitOnClose.IsChecked == true ? CloseAction.Exit : (CloseAction?)null;
|
||||
var options = new DesktopOptions(endpoint, close);
|
||||
_savingSettings = true;
|
||||
try
|
||||
{
|
||||
await _agent.SaveAsync(endpoint, _lifetime.Token);
|
||||
DesktopSettings.Save(options);
|
||||
_options = options;
|
||||
WriteLog("已保存桌面端和后台服务设置");
|
||||
ShowDashboard();
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { }
|
||||
catch (Exception ex) when (IsAgentError(ex))
|
||||
{
|
||||
SettingsMessage($"设置保存失败:{ex.Message}");
|
||||
}
|
||||
finally { _savingSettings = false; }
|
||||
}
|
||||
|
||||
private async void RefreshUps(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
if (!NutEndpoint.TryServer(HostBox.Text, PortBox.Text, out var host, out var port))
|
||||
{
|
||||
SettingsMessage("请先输入有效的 NUT 服务器地址和端口。");
|
||||
return;
|
||||
}
|
||||
using var discovery = new CancellationTokenSource();
|
||||
_discovery = discovery;
|
||||
RefreshUpsButton.IsEnabled = false;
|
||||
DiscoveredUps.IsVisible = false;
|
||||
SettingsMessage("正在获取 UPS 名称…");
|
||||
try
|
||||
{
|
||||
var names = await _agent.DiscoverAsync(host, port, discovery.Token);
|
||||
discovery.Token.ThrowIfCancellationRequested();
|
||||
if (!NutEndpoint.TryServer(HostBox.Text, PortBox.Text, out var currentHost, out var currentPort) ||
|
||||
currentHost != host || currentPort != port)
|
||||
{
|
||||
SettingsMessage("服务器地址已变更,请重新更新 UPS 名称。");
|
||||
return;
|
||||
}
|
||||
WriteLog($"NUT {host}:{port} 发现 {names.Length} 台 UPS");
|
||||
if (names.Length == 1)
|
||||
NameBox.Text = names[0];
|
||||
else if (names.Length > 1)
|
||||
{
|
||||
DiscoveredUps.ItemsSource = names;
|
||||
DiscoveredUps.SelectedItem = names.Contains(NameBox.Text) ? NameBox.Text : null;
|
||||
DiscoveredUps.IsVisible = true;
|
||||
}
|
||||
SettingsMessage(names.Length switch { 0 => "服务器没有发布可用的 UPS 名称。", 1 => "已填入 UPS 名称,保存后生效。", _ => "请选择要监控的 UPS。" });
|
||||
}
|
||||
catch (OperationCanceledException) when (discovery.IsCancellationRequested) { }
|
||||
catch (Exception ex) when (IsAgentError(ex))
|
||||
{
|
||||
if (!discovery.IsCancellationRequested)
|
||||
{
|
||||
var error = ex is OperationCanceledException ? "连接或读取超时" : ex.Message;
|
||||
SettingsMessage($"更新失败:{error}");
|
||||
WriteLog($"读取 UPS 名称失败 {host}:{port} {error}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_discovery = null;
|
||||
RefreshUpsButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void SettingsMessage(string message)
|
||||
{
|
||||
SettingsStatus.Text = message;
|
||||
SettingsStatus.IsVisible = true;
|
||||
}
|
||||
|
||||
private void SelectDiscoveredUps(object? sender, SelectionChangedEventArgs args)
|
||||
{
|
||||
if (DiscoveredUps.SelectedItem is string name) NameBox.Text = name;
|
||||
}
|
||||
|
||||
private static bool IsAgentError(Exception ex) => ex is HttpRequestException or IOException or UnauthorizedAccessException or OperationCanceledException or System.Text.Json.JsonException;
|
||||
|
||||
private async Task ObserveAgentAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_lifetime.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var state = await _agent.StatusAsync(_lifetime.Token);
|
||||
_agentState = state;
|
||||
var endpoint = state.Endpoint;
|
||||
CurrentEndpoint.Text = $"{endpoint.Name} @ {endpoint.Host}:{endpoint.Port}";
|
||||
ShutdownModeLabel.Text = state.DryRun ? "关机信号 · 模拟模式" : "关机信号";
|
||||
ShutdownSignal.Text = state.Pending is not null ? "关机倒计时进行中" : state.LastAction ?? "尚未收到关机信号";
|
||||
Render(state.Update);
|
||||
UpdateShutdownDialog(state.Pending, state.DryRun);
|
||||
}
|
||||
catch (Exception ex) when (IsAgentError(ex) && !_lifetime.IsCancellationRequested)
|
||||
{
|
||||
Render(new(_agentState?.Update.LastReading, $"本机后台服务不可用:{ex.Message}", false));
|
||||
}
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), _lifetime.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (_lifetime.IsCancellationRequested && (IsAgentError(ex) || ex is ObjectDisposedException)) { }
|
||||
}
|
||||
|
||||
private void UpdateShutdownDialog(ShutdownNotice? notice, bool dryRun)
|
||||
{
|
||||
if (_shutdownDialog?.Notice.Id == notice?.Id) return;
|
||||
_shutdownDialog?.Dismiss();
|
||||
_shutdownDialog = null;
|
||||
if (notice is null) return;
|
||||
if (OwnedWindows.FirstOrDefault(window => window is CloseDialog) is CloseDialog closeDialog)
|
||||
closeDialog.Close(null);
|
||||
Restore();
|
||||
var dialog = new ShutdownDialog(notice, dryRun, _agent);
|
||||
_shutdownDialog = dialog;
|
||||
WriteLog("后台服务收到 FSD,显示关机确认");
|
||||
_ = dialog.ShowDialog(this);
|
||||
}
|
||||
|
||||
private void Render(UpsUpdate update)
|
||||
{
|
||||
var reading = update.LastReading;
|
||||
if (reading is null && update.Error is null)
|
||||
{
|
||||
Supply.Text = "等待后台服务读取 UPS";
|
||||
Updated.Text = "等待首次读数";
|
||||
ConnectionError.IsVisible = false;
|
||||
ShowMetrics(null);
|
||||
return;
|
||||
}
|
||||
var live = update.Error is null && reading is not null;
|
||||
Supply.Text = !live ? "通讯中断" : reading!.Has("FSD") ? "收到关机信号" :
|
||||
reading.Has("LB") ? "电池电量低" : reading.Has("OB") ? "电池供电" :
|
||||
reading.Has("OL") ? "市电供电" : $"UPS 状态 {reading.Get("ups.status")}";
|
||||
Updated.Text = reading is null ? "等待首次读数" :
|
||||
$"{(live ? "更新时间" : "历史读数 · 最后读取")} {reading.At.LocalDateTime:G}";
|
||||
ConnectionError.Text = update.Error;
|
||||
ConnectionError.IsVisible = update.Error is not null;
|
||||
ShowMetrics(reading);
|
||||
var status = live ? $"UPS 状态 {reading!.Get("ups.status")}" : $"通讯中断 {update.Error}";
|
||||
if (status != _previousStatus)
|
||||
{
|
||||
WriteLog(status);
|
||||
_previousStatus = status;
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteLog(string message)
|
||||
{
|
||||
_logFailed = !DesktopSettings.Log(message);
|
||||
LogWarning.IsVisible = _logFailed;
|
||||
}
|
||||
|
||||
private void ShowMetrics(UpsReading? reading)
|
||||
{
|
||||
Charge.Text = Metric(reading, "battery.charge", "%");
|
||||
Load.Text = Metric(reading, "ups.load", "%");
|
||||
InputVoltage.Text = Metric(reading, "input.voltage", " V");
|
||||
OutputVoltage.Text = Metric(reading, "output.voltage", " V");
|
||||
}
|
||||
|
||||
private static string Metric(UpsReading? reading, string key, string unit) =>
|
||||
reading?.Get(key) is { Length: > 0 } value ? value + unit : "—";
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using Avalonia;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => AppBuilder.Configure<App>().UsePlatformDetect().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="LanUps.Desktop.ShutdownDialog" Title="UPS 关机确认" Width="440" SizeToContent="Height"
|
||||
Topmost="True" CanResize="False" ShowInTaskbar="False" WindowStartupLocation="CenterOwner">
|
||||
<StackPanel Margin="24" Spacing="12">
|
||||
<TextBlock Text="收到 UPS 关机指令" FontSize="22" FontWeight="SemiBold" />
|
||||
<TextBlock x:Name="CountdownLabel" TextWrapping="Wrap" />
|
||||
<TextBlock x:Name="ResponseStatus" TextWrapping="Wrap" IsVisible="False" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button x:Name="CancelButton" Content="取消本次" Click="CancelShutdown" />
|
||||
<Button x:Name="ConfirmButton" Content="立即关机" Click="ConfirmShutdown" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,73 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Threading;
|
||||
using LanUps.Core;
|
||||
|
||||
namespace LanUps.Desktop;
|
||||
|
||||
public sealed partial class ShutdownDialog : Window
|
||||
{
|
||||
private readonly AgentClient? _agent;
|
||||
private readonly bool _dryRun;
|
||||
private readonly DispatcherTimer _timer;
|
||||
private bool _allowClose;
|
||||
private bool _sending;
|
||||
public ShutdownNotice Notice { get; }
|
||||
|
||||
public ShutdownDialog() : this(new(Guid.Empty, DateTimeOffset.UtcNow), true, null) { }
|
||||
|
||||
internal ShutdownDialog(ShutdownNotice notice, bool dryRun, AgentClient? agent)
|
||||
{
|
||||
Notice = notice;
|
||||
_dryRun = dryRun;
|
||||
_agent = agent;
|
||||
InitializeComponent();
|
||||
if (dryRun) ConfirmButton.Content = "立即模拟关机";
|
||||
_timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
|
||||
_timer.Tick += (_, _) => RefreshCountdown();
|
||||
Opened += (_, _) => { RefreshCountdown(); _timer.Start(); };
|
||||
Closed += (_, _) => _timer.Stop();
|
||||
Closing += (_, args) =>
|
||||
{
|
||||
if (!_allowClose && args.CloseReason is WindowCloseReason.WindowClosing or WindowCloseReason.Undefined)
|
||||
args.Cancel = true;
|
||||
};
|
||||
}
|
||||
|
||||
internal void Dismiss()
|
||||
{
|
||||
_allowClose = true;
|
||||
Close();
|
||||
}
|
||||
|
||||
private void RefreshCountdown()
|
||||
{
|
||||
var seconds = Math.Max(0, (int)Math.Ceiling((Notice.Deadline - DateTimeOffset.UtcNow).TotalSeconds));
|
||||
var action = _dryRun ? "模拟关机" : "自动关机";
|
||||
CountdownLabel.Text = seconds > 0 ? $"若无人响应,设备将在 {seconds} 秒后{action}。" : $"倒计时已结束,正在等待后台服务处理{action}。";
|
||||
CancelButton.IsEnabled = ConfirmButton.IsEnabled = seconds > 0 && !_sending;
|
||||
}
|
||||
|
||||
private async void ConfirmShutdown(object? sender, RoutedEventArgs args) => await RespondAsync(true);
|
||||
private async void CancelShutdown(object? sender, RoutedEventArgs args) => await RespondAsync(false);
|
||||
|
||||
private async Task RespondAsync(bool confirm)
|
||||
{
|
||||
if (_sending || _agent is null) return;
|
||||
_sending = true;
|
||||
RefreshCountdown();
|
||||
try
|
||||
{
|
||||
await _agent.RespondAsync(Notice.Id, confirm, CancellationToken.None);
|
||||
if (IsVisible) Dismiss();
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException or OperationCanceledException or UnauthorizedAccessException or ObjectDisposedException or System.Text.Json.JsonException)
|
||||
{
|
||||
if (!IsVisible) return;
|
||||
ResponseStatus.Text = $"提交失败:{ex.Message}";
|
||||
ResponseStatus.IsVisible = true;
|
||||
_sending = false;
|
||||
RefreshCountdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Exercise the loopback API with a simulated NUT server. Never enables real shutdown."""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main(*command):
|
||||
mode = 'OL'
|
||||
with socket.create_server(('127.0.0.1', 0)) as probe:
|
||||
port = probe.getsockname()[1]
|
||||
nut = socket.create_server(('127.0.0.1', 0))
|
||||
|
||||
def serve():
|
||||
while True:
|
||||
conn, _ = nut.accept()
|
||||
with conn, conn.makefile('rb') as reader:
|
||||
request = reader.readline()
|
||||
if request == b'LIST VAR h1000m\n':
|
||||
body = f'BEGIN LIST VAR h1000m\nVAR h1000m ups.status "{mode}"\nEND LIST VAR h1000m\n'
|
||||
conn.sendall(b'ERR DATA-STALE\n' if mode == 'stale' else body.encode())
|
||||
elif request == b'LIST UPS\n':
|
||||
conn.sendall(b'BEGIN LIST UPS\nUPS h1000m "Test UPS"\nEND LIST UPS\n')
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
http = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
token_path = Path(temp) / 'agent.token'
|
||||
env = dict(os.environ, LANUPS_AGENT_PORT=str(port), LANUPS_AGENT_TOKEN=str(token_path))
|
||||
subprocess.run([*command, '--provision'], env=env, check=True)
|
||||
token = token_path.read_text().strip()
|
||||
|
||||
def call(path, method='GET', body=None, auth=True):
|
||||
headers = {'X-LanUps-Token': token} if auth else {}
|
||||
data = None
|
||||
if body is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
data = json.dumps(body).encode()
|
||||
request = urllib.request.Request(f'http://127.0.0.1:{port}/{path}', data=data, headers=headers, method=method)
|
||||
with http.open(request, timeout=2) as response:
|
||||
return json.load(response)
|
||||
|
||||
def wait(predicate, seconds=9):
|
||||
deadline = time.monotonic() + seconds
|
||||
state = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = call('status')
|
||||
if predicate(state):
|
||||
return state
|
||||
except (ConnectionError, urllib.error.URLError) as error:
|
||||
if isinstance(error, urllib.error.HTTPError):
|
||||
raise
|
||||
time.sleep(.2)
|
||||
raise AssertionError(state)
|
||||
|
||||
def flag(state):
|
||||
reading = state['update']['lastReading']
|
||||
return reading and reading['values']['ups.status']
|
||||
|
||||
def denied(path, code, method='GET', body=None, auth=True):
|
||||
try:
|
||||
call(path, method, body, auth)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == code, error.code
|
||||
else:
|
||||
raise AssertionError('Expected HTTP error')
|
||||
|
||||
def start():
|
||||
return subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL)
|
||||
|
||||
process = start()
|
||||
try:
|
||||
wait(lambda state: state['dryRun'])
|
||||
denied('status', 401, auth=False)
|
||||
endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'}
|
||||
assert call('endpoint', 'PUT', endpoint) == endpoint
|
||||
assert call(f"ups?host=127.0.0.1&port={endpoint['port']}") == ['h1000m']
|
||||
wait(lambda state: flag(state) == 'OL')
|
||||
mode = 'stale'
|
||||
wait(lambda state: state['update']['error'] and not state['pending'])
|
||||
mode = 'OB FSD'
|
||||
first = wait(lambda state: state['pending'])['pending']['id']
|
||||
denied('endpoint', 409, 'PUT', dict(endpoint, port=1))
|
||||
assert call(f'shutdown/{first}/cancel', 'POST') == 'cancel'
|
||||
wait(lambda state: state['lastAction'] == '用户取消' and not state['pending'])
|
||||
denied(f'shutdown/{first}/confirm', 409, 'POST')
|
||||
|
||||
mode = 'OL'
|
||||
wait(lambda state: flag(state) == 'OL')
|
||||
mode = 'OB FSD'
|
||||
second = wait(lambda state: state['pending'])['pending']['id']
|
||||
assert call(f'shutdown/{second}/confirm', 'POST') == 'confirm'
|
||||
wait(lambda state: '已模拟关机' in (state['lastAction'] or ''))
|
||||
|
||||
mode = 'OL'
|
||||
wait(lambda state: flag(state) == 'OL')
|
||||
mode = 'OB FSD'
|
||||
pending = wait(lambda state: state['pending'])['pending']
|
||||
deadline = datetime.datetime.fromisoformat(pending['deadline'])
|
||||
assert 56 < (deadline - datetime.datetime.now(datetime.timezone.utc)).total_seconds() <= 61
|
||||
process.terminate()
|
||||
process.wait()
|
||||
process = start()
|
||||
assert wait(lambda state: state['pending'])['pending'] == pending
|
||||
print('PASS: local authorization, settings, discovery, stale data, cancel, confirm, restart recovery', flush=True)
|
||||
result = wait(lambda state: (state['lastAction'] or '').startswith('60 秒内无响应'), 65)
|
||||
assert result['pending'] is None and datetime.datetime.now(datetime.timezone.utc) >= deadline
|
||||
print('PASS: 60-second automatic dry-run shutdown', flush=True)
|
||||
finally:
|
||||
process.terminate()
|
||||
process.wait()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(*sys.argv[1:])
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Smoke-test a published Linux Avalonia build on a disposable Xvfb display."""
|
||||
|
||||
from ctypes import CDLL, POINTER, byref, c_char_p, c_int, c_uint, c_ulong, c_void_p
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
def window_titles():
|
||||
x11 = CDLL('libX11.so.6')
|
||||
x11.XOpenDisplay.argtypes = [c_char_p]
|
||||
x11.XOpenDisplay.restype = c_void_p
|
||||
x11.XDefaultRootWindow.argtypes = [c_void_p]
|
||||
x11.XDefaultRootWindow.restype = c_ulong
|
||||
x11.XQueryTree.argtypes = [c_void_p, c_ulong, POINTER(c_ulong), POINTER(c_ulong), POINTER(POINTER(c_ulong)), POINTER(c_uint)]
|
||||
x11.XFetchName.argtypes = [c_void_p, c_ulong, POINTER(c_char_p)]
|
||||
x11.XFree.argtypes = [c_void_p]
|
||||
x11.XCloseDisplay.argtypes = [c_void_p]
|
||||
display = x11.XOpenDisplay(None)
|
||||
if not display:
|
||||
raise OSError('Run this smoke test under Xvfb')
|
||||
children = POINTER(c_ulong)()
|
||||
count = c_uint()
|
||||
titles = set()
|
||||
try:
|
||||
root = x11.XDefaultRootWindow(display)
|
||||
x11.XQueryTree(display, root, byref(c_ulong()), byref(c_ulong()), byref(children), byref(count))
|
||||
for child in children[:count.value]:
|
||||
title = c_char_p()
|
||||
if x11.XFetchName(display, child, byref(title)) and title.value:
|
||||
titles.add(title.value.decode('utf-8', errors='replace'))
|
||||
x11.XFree(title)
|
||||
return titles
|
||||
finally:
|
||||
if children:
|
||||
x11.XFree(children)
|
||||
x11.XCloseDisplay(display)
|
||||
|
||||
|
||||
def main(*command):
|
||||
now = datetime.now(timezone.utc)
|
||||
state = {
|
||||
'dryRun': True, 'lastAction': None,
|
||||
'endpoint': {'host': '127.0.0.1', 'port': 3493, 'name': 'h1000m'},
|
||||
'update': {'error': None, 'newShutdownSignal': True, 'lastReading': {
|
||||
'at': now.isoformat(), 'values': {'ups.status': 'OB FSD', 'battery.charge': '71'}}},
|
||||
'pending': {'id': '7a581f0d-9ab1-4f81-a814-1e236e1ed309', 'deadline': (now + timedelta(minutes=1)).isoformat()},
|
||||
}
|
||||
observed = threading.Event()
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
assert self.path == '/status' and self.headers['X-LanUps-Token'] == 'A' * 64
|
||||
payload = json.dumps(state).encode()
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
observed.set()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server, tempfile.TemporaryDirectory() as tmp:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
token = Path(tmp) / 'agent.token'
|
||||
token.write_text('A' * 64)
|
||||
environment = dict(os.environ, LANUPS_AGENT_PORT=str(server.server_port), LANUPS_AGENT_TOKEN=str(token), XDG_DATA_HOME=tmp)
|
||||
process = subprocess.Popen(command, env=environment)
|
||||
try:
|
||||
for _ in range(80):
|
||||
if process.poll() is not None:
|
||||
raise AssertionError(f'Desktop exited with code {process.returncode}')
|
||||
if observed.is_set() and 'UPS 关机确认' in window_titles():
|
||||
print('PASS: published Avalonia desktop read IPC state and displayed FSD confirmation', flush=True)
|
||||
return
|
||||
time.sleep(.2)
|
||||
raise AssertionError(f'FSD dialog not found: {window_titles()}')
|
||||
finally:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
server.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(*sys.argv[1:])
|
||||
@@ -0,0 +1,10 @@
|
||||
# LEDE 路由器部署
|
||||
|
||||
1. 执行 `ssh root@192.168.5.1` 登录。用 USB 数据线将 UPS 从电脑移接到路由器,通过 `/sys/bus/usb/devices/` 下的 `idVendor` 和 `idProduct` 核对设备 ID `0665:5161`。
|
||||
2. 刷新路由器的软件包列表,安装 `nut-server`、`nut-driver-blazer_usb` 和 `nut-upsc`。软件包可用性取决于固件和软件源。
|
||||
3. 在路由器的 NUT 配置中添加名为 `h1000m` 的 UPS,驱动设为 `blazer_usb`,端口设为 `auto`。让服务端监听 `127.0.0.1` 和路由器的 LAN 地址 `192.168.5.1`,TCP 端口为 `3493`。
|
||||
4. 启动服务后,在路由器运行 `upsc h1000m@127.0.0.1`,检查 `driver.name`、`ups.status` 和设备返回的电池数据。然后在电脑上启动自研监控,检查网页读数。
|
||||
|
||||
如果要配置停电自动关机,将路由器和通信路径上的交换机接到 UPS 供电,并先在客户端确认能收到状态变化。
|
||||
|
||||
[H1000M 同型号实测](https://github.com/networkupstools/nut/issues/995) · [OpenWrt 驱动包](https://openwrt.org/packages/pkgdata/nut-driver-blazer_usb)
|
||||
@@ -0,0 +1,18 @@
|
||||
# 进度与排程
|
||||
|
||||
## 当前情况
|
||||
|
||||
UPS 现已接到 LEDE。路由器识别出 `0665:5161`,已用 `blazer_usb` 读到真机数据,并从 Windows 验证了网页监控的实时读数。此前 UPS 接 Windows 时 USB 容易掉线后重连,原因待排查。2026 年 11 月 28 日完成一次真实 USB 拔插测试,路由器重新识别 USB 后约 4 秒,NUT 自动恢复连接,Windows 监控接口随后返回实时读数。连续拔插和长时间稳定性仍待验证。断线期间的数据过期标记已通过模拟测试验证。
|
||||
|
||||
本次本机联调因 8080 已被占用,监控页面使用 `http://127.0.0.1:18080`。需要复现时可在启动命令上加 `-listen 127.0.0.1:18080`。
|
||||
|
||||
## 开发排程
|
||||
|
||||
| 阶段 | 预计工期 | 工作与验收 |
|
||||
| --- | --- | --- |
|
||||
| 1. 建立基线 | 1 天 | UPS 接到 LEDE 后验证 `blazer_usb` 能读取 `ups.status` 和电量,自研监控能通过局域网读取。记录驱动日志与 USB 枚举情况。 |
|
||||
| 2. 断线恢复 | 1–2 天 | 模拟 USB 拔插、连续重连和 USB 先于驱动或晚于驱动上线。断线时标记状态过期,重连后自动恢复读取。先验证 NUT 自带的恢复能力,有缺口时再加受控重试。 |
|
||||
| 3. 稳定性与关机验证 | 1–2 天 | 做至少 24 小时运行观察。分别验证 USB 掉线、局域网中断和真实停电,确认通信中断本身不会触发误关机,并核对可确认的停电和低电量事件。 |
|
||||
| 4. 群晖 NAS 版评估 | 1 天 | 前三阶段验收后,再根据 NAS 型号和 DSM 版本实测内置网络 UPS 客户端能否连接 LEDE。若有额外功能需求或内置客户端不适配,再确定群晖版的功能、交付方式和工期。 |
|
||||
|
||||
工期从 UPS 接到 LEDE、可开始验证时起算。群晖版开发暂列候选,评估后再排实现。
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"lan-ups/internal/monitor"
|
||||
"lan-ups/internal/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
address := flag.String("nut", "192.168.5.1:3493", "NUT server address")
|
||||
name := flag.String("ups", "h1000m", "UPS name on the NUT server")
|
||||
listen := flag.String("listen", "127.0.0.1:8080", "HTTP listen address")
|
||||
interval := flag.Duration("interval", 3*time.Second, "Polling interval")
|
||||
flag.Parse()
|
||||
if _, _, err := net.SplitHostPort(*address); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if !regexp.MustCompile(`^[A-Za-z0-9_.-]+$`).MatchString(*name) || *interval < time.Second {
|
||||
log.Fatal("UPS name must contain letters, numbers, underscores, dots or hyphens; interval must be at least 1s")
|
||||
}
|
||||
|
||||
status := monitor.New(*address, *name)
|
||||
go status.Run(*interval)
|
||||
server := &http.Server{
|
||||
Addr: *listen, Handler: web.Handler(status.Snapshot),
|
||||
ReadHeaderTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second,
|
||||
}
|
||||
log.Printf("UPS dashboard listening on %s", *listen)
|
||||
log.Fatal(server.ListenAndServe())
|
||||
}
|
||||
Reference in new issue
Block a user