设备端扫码上报 + 桌面端/Android 正式包发布脚手架
AndroidStation(原中控改造为纯设备端) - 只做三件事:UDP 48899 被桌面端发现、TCP 8087 推送 USB 扫码结果、离线语音播报 - 扫码不再经过 UI:去掉逐键重绘,50ms 自动提交,同一码重复扫码也一律上报 - 离线语音种子(数字/字母/“开始打包”/欢迎语)随包安装,MediaPlayer 播放,启动把音量拉满 - 启动播报「欢迎使用溯源系统,初始化已经完成,扫码即可开始打包」 - 移除 Device Owner / 设备管理员 / lock task / 网络与 IP 设置等非普通应用能力(仅保留开机自启) - 正式签名 keystore + release 签名配置,versionName/versionCode 可由打包脚本覆盖 发布脚手架 - backend/android_client:Android 正式包构建(build.ps1 + package.config.json) - backend/scripts/deploy/publish-android.cjs + npm run android:build / android:publish - 桌面端安装包改为 download/desktop,Android 为 download/android_client; version.json 仍走 /download/version.json(老客户端写死),新增 /download/android_client/version.json - 谷歌插件随桌面端 MSI 安装到 <安装目录>\extension,工具菜单新增「复制谷歌插件地址」 - git-safety-check 增加仓库级禁区(keystore.properties / *.jks / local.properties) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
4fdc10d4a3
commit
228723e0c3
3
.githooks/pre-commit
Normal file
3
.githooks/pre-commit
Normal file
@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
# 禁止提交服务端私有配置 / 运行期产物 / 版本记录(参考 wms 的 .githooks/pre-commit)
|
||||
node backend/scripts/deploy/git-safety-check.cjs
|
||||
18
.gitignore
vendored
18
.gitignore
vendored
@ -29,6 +29,9 @@ artifacts/
|
||||
desktop/installer/out/
|
||||
*.wixpdb
|
||||
|
||||
# Android 设备端安装包产物(backend/android_client/build.ps1 生成)
|
||||
backend/android_client/out/
|
||||
|
||||
# 安装包分发目录(打包脚本复制到后端静态目录;只保留 .gitkeep)
|
||||
backend/app/public/download/*
|
||||
!backend/app/public/download/.gitkeep
|
||||
@ -41,6 +44,7 @@ logs/
|
||||
logs-*/
|
||||
run/
|
||||
tmp/
|
||||
backend/temp/
|
||||
*.log
|
||||
*.pid
|
||||
|
||||
@ -48,8 +52,19 @@ tmp/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# 前端生产构建参数不含密钥,允许提交
|
||||
!frontend/.env.production
|
||||
# 后端生产环境变量(含密码),只保留本机副本,发布时自动上传服务器
|
||||
backend/config/env.prod.sh
|
||||
config.local.js
|
||||
config.local.*.js
|
||||
# 生产配置(数据库/Redis 密码)由运维放在服务器,随发布保留,不进仓库
|
||||
config.prod.js
|
||||
|
||||
# ---------- 发布脚手架本地状态 ----------
|
||||
backend/config/deploy.config.local.cjs
|
||||
backend/versioning/*
|
||||
!backend/versioning/.gitkeep
|
||||
|
||||
# ---------- Egg 自动生成的类型声明(typings/ 由 egg-ts-helper 生成) ----------
|
||||
typings/
|
||||
@ -58,6 +73,9 @@ typings/
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
!.vscode/settings.json
|
||||
# AndroidStation 的 VS Code 任务(tools/android.ps1 的转发入口)需要入库
|
||||
!AndroidStation/.vscode/
|
||||
!AndroidStation/.vscode/tasks.json
|
||||
.idea/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
102
AndroidStation/.github/copilot-instructions.md
vendored
Normal file
102
AndroidStation/.github/copilot-instructions.md
vendored
Normal file
@ -0,0 +1,102 @@
|
||||
# AndroidStation(设备端)
|
||||
|
||||
Android TV / 电视盒子上的**扫码设备端**。它扮演网口扫码设备,让 `desktop/` 的扫码服务
|
||||
自动发现并读取 USB 扫码枪的结果。
|
||||
|
||||
## 角色
|
||||
|
||||
```
|
||||
桌面端(发现 + 连接) → UDP 48899 发现 / TCP 8087 读取扫码结果 → 本机
|
||||
```
|
||||
|
||||
- **只做设备端**:不扫描别的设备、不管理通道、不回放、没有手势登录、没有网络设置。
|
||||
- **不改 IP**:设备地址由现场网络分配;设置页只配置设备名、服务端口、发现端口和启停开关。
|
||||
- **不要搬回中控业务**:`desktop/` 才是中控/桌面端,相关逻辑不在本工程。
|
||||
|
||||
## 关键实现
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `App` | 进程启动时拉起 `StationService` |
|
||||
| `core/service/StationService` | 进程级单例:服务启停、扫码历史、UI 回调 |
|
||||
| `core/service/DiscoveryResponder` | UDP 发现应答 + JCMD 兼容 |
|
||||
| `core/service/ScanServer` | TCP 服务端,向桌面端推送扫码结果 |
|
||||
| `core/StationSettings` | 设备名 / TCP 端口 / UDP 端口 / 开关 |
|
||||
| `core/StationIdentity` | MAC、IP、型号、版本、Uptime |
|
||||
| `core/speech/BarcodeSpeaker` | 离线语音种子拼接 + MediaPlayer 播报 + 启动音量最大 |
|
||||
| `MainActivity` | 状态展示 + USB 扫码枪按键采集 |
|
||||
| `SettingsActivity` | 服务设置 |
|
||||
|
||||
## 协议约定(必须与桌面端保持一致)
|
||||
|
||||
桌面端常量在 `desktop/Services/Scan/ScanChannel.cs` 的 `ScanProtocol`:
|
||||
|
||||
- UDP 发现端口 **48899**;广播请求 `{"Type":"EP_Tool",...}`。
|
||||
- TCP 服务端口 **8087**(桌面端参数名为 `TcpPort`)。
|
||||
- SOCK 条目名 **`packcenter`**。
|
||||
- 扫码结果按 **UTF-8 + CRLF** 一行一条推送。
|
||||
- JCMD 只需支持 `10001 / 10003 / 10005 / 10017`;`20003` 只回 `RC=0`,不要重启本机。
|
||||
- 发现回复字段见 `docs/udp-48899-protocol.md` §6;`HostName` 用 UTF-8。
|
||||
|
||||
## 构建
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 build
|
||||
```
|
||||
|
||||
或:
|
||||
|
||||
```powershell
|
||||
$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
|
||||
.\gradlew.bat :app:assembleDebug
|
||||
```
|
||||
|
||||
APK:`app\build\outputs\apk\debug\app-debug.apk`
|
||||
|
||||
## 日志
|
||||
|
||||
- 统一用 `com.gztbyc.scancenter.util.L`(静态导入 `log/i/w/e`),**不要直接写 `android.util.Log`**。
|
||||
- tag 固定 `AndroidStation`;release 包需 `adb shell setprop log.tag.AndroidStation DEBUG` 才输出。
|
||||
- 不要删 `buildFeatures { buildConfig true }`,`L` 依赖 `BuildConfig.DEBUG`。
|
||||
|
||||
## 扫码热路径(必须保持快)
|
||||
|
||||
设备大概率长期不接显示器,扫码链路只允许做最少的事:
|
||||
|
||||
```
|
||||
dispatchKeyEvent → StringBuilder → commitScan → StationService.pushBarcode
|
||||
→ ScanServer 单线程 writer → 桌面端
|
||||
```
|
||||
|
||||
- **禁止**在 `dispatchKeyEvent` / `commitScan` / `pushBarcode` 里同步刷新 UI 或写日志。
|
||||
界面刷新由 `MainActivity` 的低频任务兜底(5 秒一次)。
|
||||
- **禁止**在主线程写 socket。所有推送都在 `ScanServer` 的 `station-scan-write` 线程完成。
|
||||
- **禁止去重**:重复条码也必须上报;连续扫描的重复帧由桌面端判断。
|
||||
- 扫码枪没有回车/Tab 后缀时,50ms 无输入自动提交;不要再调大。
|
||||
- 条码清理用首尾字符扫描,不要用正则。
|
||||
|
||||
## 语音播报
|
||||
|
||||
- 设备只有 `PicoTts` 且没有中文数据,**不要用 `TextToSpeech`**;用 `tools/fetch-voice-seeds.ps1`
|
||||
抓下来的 `res/raw/voice_*.wav` 离线种子。
|
||||
- 种子统一为 **44.1kHz / 立体声 / 16-bit PCM**;这台 rk3288 上 `AudioTrack` 初始化会失败,
|
||||
播放必须走 `MediaPlayer`,且放在 `station-speech` 线程。
|
||||
- 播报内容 = 条码末尾 4 个字母/数字 + 「开始打包」;同一码 2.5 秒内不重复播报,
|
||||
换码立即打断上一句。**语音去重不等于上报去重**,上报仍然逐条发。
|
||||
- 启动时把媒体音量设到最大(`MODIFY_AUDIO_SETTINGS`)。不要在扫码热路径里调音量。
|
||||
|
||||
## 代码约定
|
||||
|
||||
- Java + XML 布局,不用 Kotlin / Compose。
|
||||
- 界面文案统一放 `res/values/strings.xml`,不硬编码。
|
||||
- 主界面以遥控器为主:可点击控件必须方向键可达,并带 `state_focused` 反馈。
|
||||
- 不要再加「跳系统设置页面」的入口(厂商把部分系统页面从 dex 删了,启动会崩)。
|
||||
- 权限只需 `INTERNET`、`RECEIVE_BOOT_COMPLETED`、`MODIFY_AUDIO_SETTINGS`;这是普通用户应用,
|
||||
**不要**引入 Device Owner / 设备管理员 / lock task / 系统应用 / 任何需要 ADB 赋权的功能。
|
||||
- 开机自启只靠 `BootReceiver` + `RECEIVE_BOOT_COMPLETED`;新装后需手动启动一次。
|
||||
|
||||
## 不要做
|
||||
|
||||
- 不要恢复 `LoginActivity` / 手势 / 安全设置 / 通道管理 / 扫码回放 / 网络设置 / HTTP 条码上报。
|
||||
- 不要在本机提供改 IP、掩码、网关的写入口。
|
||||
- 不要把桌面端的 `DeviceScanner` / `ChannelConnection` / `ScanService` 逻辑复制进来。
|
||||
22
AndroidStation/.gitignore
vendored
Normal file
22
AndroidStation/.gitignore
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
*.iml
|
||||
.gradle/
|
||||
/local.properties
|
||||
|
||||
# 本机真机调试记住的设备序列号(见 tools/android.ps1)
|
||||
.dev-adb.local.json
|
||||
/.idea/
|
||||
.DS_Store
|
||||
|
||||
# 所有模块的构建产物。原来写的是 /build(只锚定根目录),
|
||||
# 结果 app/build 下上千个中间文件会被 git add 进来。
|
||||
build/
|
||||
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
*.log
|
||||
|
||||
# 正式签名密钥(不入库;发布机必须自行备份)
|
||||
keystore.properties
|
||||
keystore/
|
||||
137
AndroidStation/.vscode/tasks.json
vendored
Normal file
137
AndroidStation/.vscode/tasks.json
vendored
Normal file
@ -0,0 +1,137 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "Android: build",
|
||||
"detail": "构建 debug APK(tools/android.ps1 build)",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"build"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": [],
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "Android: install",
|
||||
"detail": "构建 + 安装到设备",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"install"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Android: run",
|
||||
"detail": "构建 + 安装 + 启动",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"run"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Android: dev",
|
||||
"detail": "构建 + 安装 + 启动 + 跟随日志(日常开发用)",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"dev"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": [],
|
||||
"isBackground": true
|
||||
},
|
||||
{
|
||||
"label": "Android: logcat",
|
||||
"detail": "只跟随日志,不构建",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"logs"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": [],
|
||||
"isBackground": true
|
||||
},
|
||||
{
|
||||
"label": "Android: devices",
|
||||
"detail": "列出已连接设备",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"devices"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Android: clean",
|
||||
"detail": "清理构建产物",
|
||||
"type": "shell",
|
||||
"command": "powershell",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"tools\\android.ps1",
|
||||
"clean"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
8
AndroidStation/AndroidStation.code-workspace
Normal file
8
AndroidStation/AndroidStation.code-workspace
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"folders": [
|
||||
{
|
||||
"path": "."
|
||||
}
|
||||
],
|
||||
"settings": {}
|
||||
}
|
||||
169
AndroidStation/README.md
Normal file
169
AndroidStation/README.md
Normal file
@ -0,0 +1,169 @@
|
||||
# AndroidStation(设备端)
|
||||
|
||||
面向 Android TV / 电视盒子的**扫码设备端**:把 USB 扫码枪的结果通过局域网推给桌面端
|
||||
(`desktop/` 的扫码服务),并且在 UDP 48899 上扮演网口扫码设备,让桌面端自动发现。
|
||||
|
||||
原「扫描中心(AndroidScanCenter)」的中控业务已整体删除:不再扫描别的设备、不再管理通道、
|
||||
不再有手势登录 / 网络设置 / 条码 HTTP 上报。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- 语言 / UI:**Java + XML 布局**(不使用 Kotlin、不使用 Compose)
|
||||
- 包名:`com.gztbyc.scancenter`(沿用原工程,便于现场覆盖安装)
|
||||
- minSdk 21 / targetSdk 28 / compileSdk 35
|
||||
- Gradle 8.11.1 + AGP 8.7.3,JDK 17
|
||||
- 依赖:仅 `androidx.appcompat`(纯 Java,无 native 库 → 与 CPU 架构无关)
|
||||
|
||||
## 工作方式
|
||||
|
||||
```
|
||||
桌面端(desktop/Services/Scan) AndroidStation
|
||||
│ UDP 48899 广播 {"Type":"EP_Tool",...} → DiscoveryResponder
|
||||
│ ← 自己的 {"MAC","HostName","Type",...} (同一个 socket 回复)
|
||||
│
|
||||
│ TCP 8087 主动连接 → ScanServer(服务端)
|
||||
│ ← 扫码结果(UTF-8 + CRLF) USB 扫码枪(键盘 HID)
|
||||
```
|
||||
|
||||
- **允许被发现**:`DiscoveryResponder` 绑定 UDP 48899,收到发现广播就按设备固件的字段回复
|
||||
(协议见 [`docs/udp-48899-protocol.md`](docs/udp-48899-protocol.md))。
|
||||
- **扫码上报**:`ScanServer` 监听 TCP 8087,桌面端连上后,主界面收到的每一条扫码结果
|
||||
都会按行推送过去。桌面端下发的扫码枪串口设置指令会被读取并丢弃(本机是 USB HID)。
|
||||
- **兼容桌面端添加通道**:响应 JCMD `10001 / 10003 / 10005 / 10017`,报出一条
|
||||
`packcenter / TCP-SERVER / 8087` 的 SOCK 条目;桌面端写 `SYS.HostName` 会更新设备名,
|
||||
写 `SOCK.LocalPort` 会改本地服务端口。`20003` 只确认,不重启本机。
|
||||
- **不改 IP**:网络参数只读上报,设置页没有改 IP / 掩码 / 网关的入口。
|
||||
|
||||
## 主界面
|
||||
|
||||
- 设备名称 / MAC / IP / 型号版本 / 服务与发现状态 / 累计扫码。
|
||||
- 最近 8 条扫码记录(**每 5 秒才刷新一次**,不参与扫码热路径)。
|
||||
- USB 扫码枪是键盘设备:在 Activity 层统一收键,连续可打印字符攒成一条条码,
|
||||
回车/Tab 立即提交;没有后缀时停手 **50ms** 自动提交。
|
||||
- 底部「服务设置」「清空记录」两个按钮可用遥控器操作。
|
||||
- `FLAG_KEEP_SCREEN_ON` 保证长期不接显示器时 Activity 仍保持前台、服务不被挂起。
|
||||
|
||||
### 扫码性能约定(重要)
|
||||
|
||||
设备长期不接显示器,扫码路径必须尽量短:
|
||||
|
||||
```
|
||||
按键 → 追加缓冲 → 提交 → StationService 入队 → 后台写线程 → 桌面端
|
||||
```
|
||||
|
||||
- **按键/扫码回调里不同步刷新任何 UI、不写日志**;界面由 1 秒的时钟和 5 秒一次的状态刷新兜底。
|
||||
- socket 写入只在 `station-scan-write` 单线程里做,避免主线程 `NetworkOnMainThreadException`,
|
||||
同时保证多条扫码按顺序发出。
|
||||
- **不做任何去重**:同一个条码连续扫到多少次就上报多少次,重复帧由桌面端自己判断。
|
||||
- 条码校验只做首尾非字母数字清理 + 4~64 位长度检查,不用正则。
|
||||
|
||||
## 语音播报(离线)
|
||||
|
||||
设备没有显示器,扫码后要能听到「后四位 + 开始打包」。
|
||||
|
||||
- 设备上只有 `PicoTts` 且**没有中文语音数据**,所以运行时**不用 TextToSpeech**。
|
||||
- 用 `tools/fetch-voice-seeds.ps1` 从现场语音服务(`http://tbdata.gztbyc.com/voice/<文本>`)
|
||||
一次性抓取 `0-9`、`A-Z`、`开始打包`,统一转成 **44.1kHz / 立体声 / 16-bit PCM**,
|
||||
放到 `app/src/main/res/raw/voice_*.wav`;运行时只读本地资源,**断网也能播报**。
|
||||
- 播放用系统 `MediaPlayer` 读临时拼接的 WAV(这台 rk3288 的 `AudioTrack` 初始化会失败),
|
||||
在 `station-speech` 独立线程完成,不阻塞扫码上报。
|
||||
- 同一串条码 2.5 秒内不重复播报(连续扫描的重复帧);换了条码立即打断上一句播最新的。
|
||||
**上报不受影响**:重复条码仍然逐条发送。
|
||||
- 语音内容:条码末尾 4 个字母/数字(标点跳过)+ 「开始打包」。
|
||||
- 启动时 `BarcodeSpeaker.maximizeVolume` 把媒体音量设为最大(实测 `11 -> 15`)。
|
||||
需要 `MODIFY_AUDIO_SETTINGS` 普通权限。
|
||||
- 重新生成种子:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1 -Force
|
||||
```
|
||||
|
||||
脚本依赖 `desktop/native/ffmpeg/ffmpeg.exe`;生成的 WAV 需要一起提交。
|
||||
|
||||
## 服务设置
|
||||
|
||||
只保留服务参数:
|
||||
|
||||
| 项 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 设备名称 | `Build.MODEL` / `工位终端` | 广播里的 `HostName`,桌面端用它显示通道名 |
|
||||
| 扫码服务端口(TCP) | **8087** | 桌面端连上来读扫码结果 |
|
||||
| 设备发现端口(UDP) | **48899** | 桌面端发现广播的目标端口 |
|
||||
| 启用扫码服务 | 开 | 关掉后不监听 TCP |
|
||||
| 允许被桌面端发现 | 开 | 关掉后不应答 UDP 广播 |
|
||||
|
||||
⚠️ 修改端口后要和桌面端约定保持一致(桌面端常量见
|
||||
`desktop/Services/Scan/ScanChannel.cs` 的 `ScanProtocol`)。
|
||||
|
||||
## 常用命令
|
||||
|
||||
所有构建/装机/抓日志统一走 `tools/android.ps1`(`.vscode/tasks.json` 只做转发),
|
||||
脚本内会自动探测 JDK 与 adb:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 dev
|
||||
```
|
||||
|
||||
任务:`build` / `install` / `run` / `dev` / `logs` / `clean` / `devices`;
|
||||
选项:`-Variant` / `-Serial` / `-CleanFirst` / `-NoLaunch` / `-NoLogcat`。
|
||||
|
||||
直接用 Gradle 也可以(需自行设置 `JAVA_HOME`,本机 `java` 不在 PATH):
|
||||
|
||||
```powershell
|
||||
$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
|
||||
.\gradlew.bat :app:assembleDebug
|
||||
```
|
||||
|
||||
APK 产物:`app\build\outputs\apk\debug\app-debug.apk`
|
||||
|
||||
## 正式包(签名 + 发布)
|
||||
|
||||
release 包用仓库根目录 `keystore/packservice-release.jks` 签名,密码放在 `keystore.properties`
|
||||
(两者都被 `.gitignore` 忽略,**发布机必须自行备份**;丢了就只能换包名重新发)。
|
||||
|
||||
```powershell
|
||||
# 只构建正式包(产物 app\build\outputs\apk\release\app-release.apk)
|
||||
$env:JAVA_HOME='C:\Users\lfmingren\AppData\Local\Programs\EclipseAdoptium\jdk-17.0.20.1+1'
|
||||
.\gradlew.bat :app:assembleRelease -PversionName=1.0.1 -PversionCode=10001
|
||||
```
|
||||
|
||||
发布(构建 + 上传到服务器 `download/android_client/`)统一走后端脚手架,配置和桌面端同套路:
|
||||
|
||||
```powershell
|
||||
cd ..\backend
|
||||
npm run android:build # 只构建(dry-run),产物在 backend\android_client\out
|
||||
npm run android:publish # 构建 + 上传 + 刷新 nginx
|
||||
```
|
||||
|
||||
下载地址 `https://<域名>/download/android_client/YuncangScan-<版本>.apk`
|
||||
(版本信息 `.../android_client/version.json`)。
|
||||
|
||||
## 日志
|
||||
|
||||
- 统一用 `com.gztbyc.scancenter.util.L`(静态导入后 `log(...)` / `i(...)` / `w(...)` / `e(...)`),
|
||||
**不要直接写 `android.util.Log`**。
|
||||
- tag 固定为 `AndroidStation`,类名+方法名+行号自动附在消息里;单条超 3000 字符自动分段。
|
||||
- release 包默认不输出,需 `adb shell setprop log.tag.AndroidStation DEBUG` 才打开。
|
||||
- **新增代码必须保留日志链路可用**:不要删掉 `buildFeatures { buildConfig true }`,
|
||||
`L` 依赖 `BuildConfig.DEBUG`。
|
||||
|
||||
## 安装与开机启动
|
||||
|
||||
- 这是**普通用户应用**:只需要 `INTERNET`、`RECEIVE_BOOT_COMPLETED`、
|
||||
`MODIFY_AUDIO_SETTINGS` 三个普通权限,`/data` 直接安装即可。
|
||||
- 不依赖 Device Owner / 设备管理员 / lock task / 系统应用 / 任何 ADB 赋权。
|
||||
- `BootReceiver` 监听 `BOOT_COMPLETED`,开机后自动拉起 `MainActivity`。
|
||||
⚠️ Android 的既定行为:**新装后必须手动启动一次**,应用才脱离 stopped 状态,
|
||||
之后重启才会收到开机广播。
|
||||
- 主界面不在后台驻留额外服务;扫码服务随应用进程生命周期运行。
|
||||
|
||||
## 约定
|
||||
|
||||
- 依赖仓库走阿里云镜像,Gradle 分发走腾讯云镜像,改动仓库配置时保持国内源优先。
|
||||
- 主界面以遥控器为主:可点击控件必须方向键可达,并在 `res/drawable/bg_button.xml`
|
||||
这类 selector 中提供 `state_focused` 视觉反馈。
|
||||
- 界面文案统一放 `res/values/strings.xml`,不硬编码在 XML / Java 中。
|
||||
- **不要再加「跳系统设置页面」的入口**:这台盒子的 Settings 清单里声明了一些页面,
|
||||
但厂商把它们从 dex 里删掉了,用组件名启动会让系统设置当场崩。
|
||||
- **不要再把中控逻辑搬回来**(设备扫描 / 通道管理 / 回放 / 手势 / 网络设置 / HTTP 上报)。
|
||||
本工程只负责「当一台扫码设备」。
|
||||
87
AndroidStation/app/build.gradle
Normal file
87
AndroidStation/app/build.gradle
Normal file
@ -0,0 +1,87 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
|
||||
// 正式签名:keystore.properties 不入库(见 .gitignore);没有它时 debug 构建不受影响,
|
||||
// release 构建会退回 debug 签名,正式发布脚本会先检查这个文件。
|
||||
def keystorePropertiesFile = rootProject.file('keystore.properties')
|
||||
def keystoreProperties = new Properties()
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
// 发布脚本可以传 -PversionName=x.y.z -PversionCode=n 覆盖
|
||||
def appVersionCode = (project.findProperty('versionCode') ?: '1').toString().toInteger()
|
||||
def appVersionName = (project.findProperty('versionName') ?: '1.0.0').toString()
|
||||
|
||||
android {
|
||||
namespace 'com.gztbyc.scancenter'
|
||||
compileSdk 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.gztbyc.scancenter"
|
||||
minSdk 21
|
||||
targetSdk 28
|
||||
versionCode appVersionCode
|
||||
versionName appVersionName
|
||||
|
||||
// 本工程是纯 Java,APK 内 lib/ 为空,与 CPU 架构无关(arm32/arm64/x86 通用),
|
||||
// 因此这里不需要限制 ABI。
|
||||
// 一旦引入带 .so 的依赖(如 ML Kit 条码识别或任何 native 库),请取消下面注释,
|
||||
// 否则多套架构的库会被全部打进包内,包体成倍膨胀:
|
||||
// ndk {
|
||||
// abiFilters 'armeabi-v7a', 'arm64-v8a' // 排除 x86,只保留盒子/手机实际用到的架构
|
||||
// }
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
release {
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
storeFile rootProject.file(keystoreProperties['storeFile'])
|
||||
storePassword keystoreProperties['storePassword']
|
||||
keyAlias keystoreProperties['keyAlias']
|
||||
keyPassword keystoreProperties['keyPassword']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
}
|
||||
release {
|
||||
minifyEnabled false
|
||||
// 有正式 keystore 就用正式签名;没有时退回 debug,保证本地仍能 assembleRelease 验证
|
||||
signingConfig keystorePropertiesFile.exists() ? signingConfigs.release : signingConfigs.debug
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
// util/L.java 依赖 BuildConfig.DEBUG 决定是否输出日志;AGP 8 起 buildConfig 默认关闭
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
encoding = 'UTF-8'
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources {
|
||||
excludes += ['META-INF/*.kotlin_module']
|
||||
}
|
||||
}
|
||||
|
||||
lint {
|
||||
// targetSdk 28 是为在旧 TV 盒子上避开分区存储限制而刻意选择的,不发布 Google Play。
|
||||
// lintVitalRelease 会因 ExpiredTargetSdkVersion 直接中断 release 构建,这里只关掉这一条,
|
||||
// 其余 lint 检查保持开启。
|
||||
disable 'ExpiredTargetSdkVersion'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||
}
|
||||
12
AndroidStation/app/proguard-rules.pro
vendored
Normal file
12
AndroidStation/app/proguard-rules.pro
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
# 当前 release 未开启混淆(minifyEnabled = false),以下规则在启用混淆后才生效。
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# 开启混淆时直接移除所有日志调用,避免调试信息进入正式包。
|
||||
# 注意:L 类内部已用 BuildConfig.DEBUG 做了运行期开关,这里是编译期的第二道保险。
|
||||
-assumenosideeffects class android.util.Log {
|
||||
public static *** d(...);
|
||||
public static *** v(...);
|
||||
public static *** i(...);
|
||||
public static *** w(...);
|
||||
public static *** println(...);
|
||||
}
|
||||
74
AndroidStation/app/src/main/AndroidManifest.xml
Normal file
74
AndroidStation/app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- 局域网设备发现(UDP)与扫码推送(TCP)都只需要建 socket -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- 启动时把媒体音量拉到最大(普通权限,装上即授予) -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- 开机自启动:工位设备断电重启后不用人去点图标 -->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
|
||||
<!-- Android TV 支持:required=false 表示同一份包也能装到手机/平板上 -->
|
||||
<uses-feature
|
||||
android:name="android.software.leanback"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.touchscreen"
|
||||
android:required="false" />
|
||||
|
||||
<!-- 本应用只支持横屏 -->
|
||||
<uses-feature
|
||||
android:name="android.hardware.screen.landscape"
|
||||
android:required="true" />
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
android:allowBackup="true"
|
||||
android:banner="@drawable/app_banner"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AndroidStation">
|
||||
|
||||
<!-- 设备端主界面:只展示状态并接收 USB 扫码枪输入 -->
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:screenOrientation="landscape">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<!-- 电视桌面入口 -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
<!-- 普通桌面入口 -->
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- 服务设置:不导出,只从主界面进入 -->
|
||||
<activity
|
||||
android:name=".SettingsActivity"
|
||||
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
|
||||
android:exported="false"
|
||||
android:screenOrientation="landscape"
|
||||
android:windowSoftInputMode="adjustPan" />
|
||||
|
||||
<!-- 开机自启动。BOOT_COMPLETED 属于隐式广播限制的豁免项,静态注册在 Android 8+ 仍然有效。 -->
|
||||
<receiver
|
||||
android:name=".receiver.BootReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter android:priority="1000">
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@ -0,0 +1,32 @@
|
||||
package com.gztbyc.scancenter;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
|
||||
import com.gztbyc.scancenter.core.service.StationService;
|
||||
import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
|
||||
|
||||
/**
|
||||
* 持有进程级单例。
|
||||
*
|
||||
* <p>发现应答和扫码服务属于整个进程,不挂在页面上:页面重建、切换前后台都不能让
|
||||
* 桌面端的连接断开,也不能让设备从局域网里消失。
|
||||
*/
|
||||
public class App extends Application {
|
||||
|
||||
private static Context context;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
context = getApplicationContext();
|
||||
// 先把发现/扫码服务拉起来,语音里才能说「初始化已经完成」
|
||||
StationService.instance().start(context);
|
||||
// 设备长期不接显示器:启动就把音量拉满,并准备好离线语音种子/欢迎语
|
||||
BarcodeSpeaker.instance().start(context);
|
||||
}
|
||||
|
||||
public static Context context() {
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,400 @@
|
||||
package com.gztbyc.scancenter;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.gztbyc.scancenter.core.StationIdentity;
|
||||
import com.gztbyc.scancenter.core.StationSettings;
|
||||
import com.gztbyc.scancenter.core.service.StationService;
|
||||
import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import static com.gztbyc.scancenter.util.L.i;
|
||||
import static com.gztbyc.scancenter.util.L.w;
|
||||
|
||||
/**
|
||||
* 设备端主界面:显示本机身份、服务状态和最近扫码结果。
|
||||
*
|
||||
* <p>USB 扫码枪是键盘设备,这里在 Activity 层统一收键(不依赖某个输入框有没有焦点):
|
||||
* 连续可打印字符攒成一条条码,回车/Tab 立即提交;没有后缀时停手
|
||||
* {@link #FLUSH_DELAY_MS} 后自动提交,兼容不带后缀的扫码枪。
|
||||
*
|
||||
* <p><b>扫码热路径不碰 UI</b>:按键只追加到缓冲并立即提交,不同步刷新任何 TextView;
|
||||
* 界面每 {@link #UI_REFRESH_TICKS} 秒才刷新一次。设备长期不接显示器时,
|
||||
* 这条路径上唯一的耗时就是按键处理 + 把数据丢给后台推送线程。
|
||||
*/
|
||||
public class MainActivity extends AppCompatActivity {
|
||||
|
||||
/** 扫码枪没有回车后缀时,停手多久算一条扫完(USB HID 每字符通常 <5ms,50ms 足够) */
|
||||
private static final long FLUSH_DELAY_MS = 50L;
|
||||
|
||||
/** 界面信息刷新间隔(秒)。扫码本身不等界面,这里只为偶尔接显示器时能看状态 */
|
||||
private static final int UI_REFRESH_TICKS = 5;
|
||||
|
||||
/** 一条条码最多这么多字符;超过就丢弃重来,避免串口噪声无限累积 */
|
||||
private static final int MAX_INPUT = 128;
|
||||
|
||||
/** 扫码枪尾部回车可能比自动提交晚到,这段时间内要吃掉它,不能让它点到按钮 */
|
||||
private static final long SWALLOW_ENTER_MS = 1200L;
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
private final StringBuilder scanBuffer = new StringBuilder();
|
||||
private final SimpleDateFormat clockFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
|
||||
|
||||
private final StationService service = StationService.instance();
|
||||
|
||||
private TextView deviceNameView;
|
||||
private TextView clockView;
|
||||
private TextView infoNameView;
|
||||
private TextView infoMacView;
|
||||
private TextView infoIpView;
|
||||
private TextView infoVersionView;
|
||||
private TextView infoServiceView;
|
||||
private TextView infoDiscoveryView;
|
||||
private TextView infoTotalView;
|
||||
private TextView lastCodeView;
|
||||
private TextView lastTimeView;
|
||||
private TextView recentView;
|
||||
|
||||
private long lastCommitMs;
|
||||
private boolean listening;
|
||||
private int tick;
|
||||
|
||||
private final Runnable clockTask = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
renderClock();
|
||||
tick++;
|
||||
// 扫码热路径不刷新界面;这里只是低频兜底,避免每来一条码就重排布局
|
||||
if (tick % UI_REFRESH_TICKS == 0) {
|
||||
renderState();
|
||||
}
|
||||
handler.postDelayed(this, 1000L);
|
||||
}
|
||||
};
|
||||
|
||||
private final Runnable flushTask = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (scanBuffer.length() > 0) {
|
||||
commitScan();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final StationService.Listener listener = new StationService.Listener() {
|
||||
@Override
|
||||
public void onStateChanged() {
|
||||
renderState();
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
applyImmersiveMode();
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
|
||||
deviceNameView = findViewById(R.id.tv_device_name);
|
||||
clockView = findViewById(R.id.tv_clock);
|
||||
infoNameView = findViewById(R.id.tv_info_name);
|
||||
infoMacView = findViewById(R.id.tv_info_mac);
|
||||
infoIpView = findViewById(R.id.tv_info_ip);
|
||||
infoVersionView = findViewById(R.id.tv_info_version);
|
||||
infoServiceView = findViewById(R.id.tv_info_service);
|
||||
infoDiscoveryView = findViewById(R.id.tv_info_discovery);
|
||||
infoTotalView = findViewById(R.id.tv_info_total);
|
||||
lastCodeView = findViewById(R.id.tv_last_code);
|
||||
lastTimeView = findViewById(R.id.tv_last_time);
|
||||
recentView = findViewById(R.id.tv_recent);
|
||||
|
||||
Button settings = findViewById(R.id.btn_settings);
|
||||
settings.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
|
||||
}
|
||||
});
|
||||
|
||||
Button clear = findViewById(R.id.btn_clear);
|
||||
clear.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
service.clearHistory();
|
||||
Toast.makeText(MainActivity.this, R.string.main_cleared, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
|
||||
BarcodeSpeaker.instance().start(this);
|
||||
service.start(this);
|
||||
renderClock();
|
||||
renderState();
|
||||
i("设备端主界面启动", "MAC", StationIdentity.mac(this), "IP", StationIdentity.ip());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
if (!listening) {
|
||||
listening = true;
|
||||
service.addListener(listener);
|
||||
}
|
||||
handler.post(clockTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
handler.removeCallbacks(clockTask);
|
||||
handler.removeCallbacks(flushTask);
|
||||
// 中途离开页面(比如进设置)时不要留下半条条码,回来会和新输入粘在一起
|
||||
scanBuffer.setLength(0);
|
||||
if (listening) {
|
||||
listening = false;
|
||||
service.removeListener(listener);
|
||||
}
|
||||
super.onStop();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
renderState();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
handler.removeCallbacks(clockTask);
|
||||
handler.removeCallbacks(flushTask);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private void renderClock() {
|
||||
if (clockView != null) {
|
||||
clockView.setText(clockFormat.format(new Date()));
|
||||
}
|
||||
}
|
||||
|
||||
private void renderState() {
|
||||
if (deviceNameView == null) {
|
||||
return;
|
||||
}
|
||||
deviceNameView.setText(StationSettings.deviceName(this));
|
||||
infoNameView.setText(StationSettings.deviceName(this));
|
||||
infoMacView.setText(StationIdentity.displayMac(this));
|
||||
|
||||
String ip = StationIdentity.ip();
|
||||
infoIpView.setText(ip.isEmpty() ? getString(R.string.value_unknown) : ip);
|
||||
infoVersionView.setText(getString(R.string.main_version_value,
|
||||
StationIdentity.MODEL, StationIdentity.version()));
|
||||
infoServiceView.setText(serviceStatusText());
|
||||
infoDiscoveryView.setText(discoveryStatusText());
|
||||
infoTotalView.setText(getString(R.string.main_total_value, service.totalScans()));
|
||||
|
||||
String code = service.lastCode();
|
||||
if (code.isEmpty()) {
|
||||
lastCodeView.setText(R.string.main_waiting);
|
||||
lastTimeView.setText("");
|
||||
}
|
||||
else {
|
||||
lastCodeView.setText(code);
|
||||
long atMs = service.lastScanAt();
|
||||
lastTimeView.setText(getString(R.string.main_last_time,
|
||||
clockFormat.format(new Date(atMs))));
|
||||
}
|
||||
|
||||
List<StationService.ScanEntry> history = service.history();
|
||||
if (history.isEmpty()) {
|
||||
recentView.setText(R.string.main_recent_empty);
|
||||
}
|
||||
else {
|
||||
int limit = Math.min(history.size(), 8);
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (int index = 0; index < limit; index++) {
|
||||
StationService.ScanEntry entry = history.get(index);
|
||||
if (text.length() > 0) {
|
||||
text.append('\n');
|
||||
}
|
||||
text.append(clockFormat.format(new Date(entry.atMs)))
|
||||
.append(" ")
|
||||
.append(entry.code);
|
||||
}
|
||||
recentView.setText(text.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private String serviceStatusText() {
|
||||
if (!StationSettings.serviceEnabled(this)) {
|
||||
return getString(R.string.status_disabled);
|
||||
}
|
||||
if (service.isServiceRunning()) {
|
||||
return getString(R.string.main_service_running, service.servicePort(), service.clientCount());
|
||||
}
|
||||
String error = service.serviceError();
|
||||
if (error != null && !error.isEmpty()) {
|
||||
return getString(R.string.main_service_failed, error);
|
||||
}
|
||||
return getString(R.string.status_starting);
|
||||
}
|
||||
|
||||
private String discoveryStatusText() {
|
||||
if (!StationSettings.discoveryEnabled(this)) {
|
||||
return getString(R.string.status_disabled);
|
||||
}
|
||||
if (service.isDiscoveryRunning()) {
|
||||
return getString(R.string.main_discovery_running, service.discoveryPort());
|
||||
}
|
||||
String error = service.discoveryError();
|
||||
if (error != null && !error.isEmpty()) {
|
||||
return getString(R.string.main_discovery_failed, error);
|
||||
}
|
||||
return getString(R.string.status_starting);
|
||||
}
|
||||
|
||||
/**
|
||||
* 键盘扫码枪的输入在 Activity 层截获:
|
||||
* 方向键/OK 键仍然交给焦点系统,只有可打印字符和回车属于扫码内容。
|
||||
*/
|
||||
@Override
|
||||
public boolean dispatchKeyEvent(KeyEvent event) {
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN) {
|
||||
int keyCode = event.getKeyCode();
|
||||
|
||||
if (keyCode == KeyEvent.KEYCODE_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_TAB) {
|
||||
if (scanBuffer.length() > 0) {
|
||||
commitScan();
|
||||
return true;
|
||||
}
|
||||
// 自动提交后扫码枪的尾回车/Tab 才到:吃掉,别让它触发当前焦点按钮
|
||||
if (SystemClock.elapsedRealtime() - lastCommitMs < SWALLOW_ENTER_MS) {
|
||||
return true;
|
||||
}
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
if (keyCode == KeyEvent.KEYCODE_DEL) {
|
||||
if (scanBuffer.length() > 0) {
|
||||
scanBuffer.setLength(scanBuffer.length() - 1);
|
||||
return true;
|
||||
}
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
if (isInterruptKey(keyCode) && scanBuffer.length() > 0) {
|
||||
// 方向键/返回等操作说明这次扫码被打断了;修饰键(Shift)不能算
|
||||
scanBuffer.setLength(0);
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
int unicode = event.getUnicodeChar(event.getMetaState());
|
||||
if (unicode >= 0x20 && unicode != 0x7F
|
||||
&& !event.isCtrlPressed() && !event.isAltPressed() && !event.isMetaPressed()) {
|
||||
if (scanBuffer.length() >= MAX_INPUT) {
|
||||
scanBuffer.setLength(0);
|
||||
}
|
||||
scanBuffer.append((char) unicode);
|
||||
handler.removeCallbacks(flushTask);
|
||||
handler.postDelayed(flushTask, FLUSH_DELAY_MS);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
private void commitScan() {
|
||||
handler.removeCallbacks(flushTask);
|
||||
String raw = scanBuffer.toString();
|
||||
scanBuffer.setLength(0);
|
||||
lastCommitMs = SystemClock.elapsedRealtime();
|
||||
|
||||
String code = cleanBarcode(raw);
|
||||
if (code == null) {
|
||||
if (!raw.isEmpty()) {
|
||||
w("忽略非法扫码内容", raw);
|
||||
}
|
||||
return;
|
||||
}
|
||||
service.pushBarcode(code);
|
||||
}
|
||||
|
||||
private static boolean isInterruptKey(int keyCode) {
|
||||
switch (keyCode) {
|
||||
case KeyEvent.KEYCODE_DPAD_UP:
|
||||
case KeyEvent.KEYCODE_DPAD_DOWN:
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT:
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT:
|
||||
case KeyEvent.KEYCODE_DPAD_CENTER:
|
||||
case KeyEvent.KEYCODE_ESCAPE:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 与桌面端 {@code ScanProtocol.CleanBarcode} 一致:首尾非字母数字削掉,4~64 位。
|
||||
*
|
||||
* <p>热路径上不用正则:手工扫首尾比 {@code replaceAll} 少两次 Pattern 匹配和字符串分配。
|
||||
* 注意<b>不做任何去重</b>——重复条码也必须原样上报。
|
||||
*/
|
||||
private static String cleanBarcode(String raw) {
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
int start = 0;
|
||||
int end = raw.length();
|
||||
while (start < end && !isAsciiAlnum(raw.charAt(start))) {
|
||||
start++;
|
||||
}
|
||||
while (end > start && !isAsciiAlnum(raw.charAt(end - 1))) {
|
||||
end--;
|
||||
}
|
||||
int length = end - start;
|
||||
if (length < 4 || length > 64) {
|
||||
return null;
|
||||
}
|
||||
return raw.substring(start, end);
|
||||
}
|
||||
|
||||
private static boolean isAsciiAlnum(char value) {
|
||||
return (value >= '0' && value <= '9')
|
||||
|| (value >= 'A' && value <= 'Z')
|
||||
|| (value >= 'a' && value <= 'z');
|
||||
}
|
||||
|
||||
private void applyImmersiveMode() {
|
||||
getWindow().getDecorView().setSystemUiVisibility(
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
|
||||
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
| View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
if (hasFocus) {
|
||||
applyImmersiveMode();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,161 @@
|
||||
package com.gztbyc.scancenter;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.SwitchCompat;
|
||||
|
||||
import com.gztbyc.scancenter.core.StationIdentity;
|
||||
import com.gztbyc.scancenter.core.StationSettings;
|
||||
import com.gztbyc.scancenter.core.service.StationService;
|
||||
|
||||
/**
|
||||
* 服务设置:只配置设备名、扫码服务端口、发现端口和启停开关。
|
||||
*
|
||||
* <p>按现场要求<b>不提供改 IP 的入口</b>:设备地址由网络分配,应用只负责应答发现和推扫码数据。
|
||||
*/
|
||||
public class SettingsActivity extends AppCompatActivity {
|
||||
|
||||
private EditText nameField;
|
||||
private EditText servicePortField;
|
||||
private EditText discoveryPortField;
|
||||
private SwitchCompat serviceSwitch;
|
||||
private SwitchCompat discoverySwitch;
|
||||
private TextView statusView;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_settings);
|
||||
|
||||
nameField = findViewById(R.id.et_device_name);
|
||||
servicePortField = findViewById(R.id.et_service_port);
|
||||
discoveryPortField = findViewById(R.id.et_discovery_port);
|
||||
serviceSwitch = findViewById(R.id.sw_service_enabled);
|
||||
discoverySwitch = findViewById(R.id.sw_discovery_enabled);
|
||||
statusView = findViewById(R.id.tv_settings_status);
|
||||
|
||||
nameField.setText(StationSettings.deviceName(this));
|
||||
servicePortField.setText(String.valueOf(StationSettings.servicePort(this)));
|
||||
discoveryPortField.setText(String.valueOf(StationSettings.discoveryPort(this)));
|
||||
serviceSwitch.setChecked(StationSettings.serviceEnabled(this));
|
||||
discoverySwitch.setChecked(StationSettings.discoveryEnabled(this));
|
||||
|
||||
Button save = findViewById(R.id.btn_save);
|
||||
save.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
saveSettings();
|
||||
}
|
||||
});
|
||||
|
||||
Button back = findViewById(R.id.btn_back);
|
||||
back.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
|
||||
serviceSwitch.setOnCheckedChangeListener((button, checked) -> renderStatus());
|
||||
discoverySwitch.setOnCheckedChangeListener((button, checked) -> renderStatus());
|
||||
renderStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
renderStatus();
|
||||
}
|
||||
|
||||
private void saveSettings() {
|
||||
String name = nameField.getText().toString().trim();
|
||||
if (name.isEmpty()) {
|
||||
nameField.setError(getString(R.string.settings_error_name));
|
||||
nameField.requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
int servicePort = parsePort(servicePortField);
|
||||
if (servicePort < 0) {
|
||||
servicePortField.setError(getString(R.string.settings_error_service_port));
|
||||
servicePortField.requestFocus();
|
||||
return;
|
||||
}
|
||||
int discoveryPort = parsePort(discoveryPortField);
|
||||
if (discoveryPort < 0) {
|
||||
discoveryPortField.setError(getString(R.string.settings_error_discovery_port));
|
||||
discoveryPortField.requestFocus();
|
||||
return;
|
||||
}
|
||||
if (servicePort == discoveryPort) {
|
||||
discoveryPortField.setError(getString(R.string.settings_error_same_port));
|
||||
discoveryPortField.requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
StationSettings.save(this, name, servicePort, discoveryPort,
|
||||
serviceSwitch.isChecked(), discoverySwitch.isChecked());
|
||||
StationService.instance().restart();
|
||||
renderStatus();
|
||||
|
||||
String error = currentError();
|
||||
if (error.isEmpty()) {
|
||||
Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
else {
|
||||
Toast.makeText(this, getString(R.string.settings_saved_with_error, error),
|
||||
Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
private static int parsePort(EditText field) {
|
||||
try {
|
||||
int port = Integer.parseInt(field.getText().toString().trim());
|
||||
return port >= 1 && port <= 65535 ? port : -1;
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private String currentError() {
|
||||
StationService service = StationService.instance();
|
||||
if (StationSettings.serviceEnabled(this) && !service.isServiceRunning()) {
|
||||
String error = service.serviceError();
|
||||
return error == null || error.isEmpty() ? getString(R.string.status_starting) : error;
|
||||
}
|
||||
if (StationSettings.discoveryEnabled(this) && !service.isDiscoveryRunning()) {
|
||||
String error = service.discoveryError();
|
||||
return error == null || error.isEmpty() ? getString(R.string.status_starting) : error;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private void renderStatus() {
|
||||
StationService service = StationService.instance();
|
||||
String ip = StationIdentity.ip();
|
||||
String serviceState = serviceSwitch.isChecked()
|
||||
? (service.isServiceRunning()
|
||||
? getString(R.string.main_service_running, service.servicePort(), service.clientCount())
|
||||
: getString(R.string.status_starting))
|
||||
: getString(R.string.status_disabled);
|
||||
String discoveryState = discoverySwitch.isChecked()
|
||||
? (service.isDiscoveryRunning()
|
||||
? getString(R.string.main_discovery_running, service.discoveryPort())
|
||||
: getString(R.string.status_starting))
|
||||
: getString(R.string.status_disabled);
|
||||
|
||||
statusView.setText(getString(R.string.settings_status,
|
||||
StationIdentity.displayMac(this),
|
||||
ip.isEmpty() ? getString(R.string.value_unknown) : ip,
|
||||
serviceState,
|
||||
discoveryState));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,214 @@
|
||||
package com.gztbyc.scancenter.core;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.SystemClock;
|
||||
import android.provider.Settings;
|
||||
|
||||
import com.gztbyc.scancenter.BuildConfig;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 本机在「设备」身份下的固定信息。
|
||||
*
|
||||
* <p>MAC 是设备发现的唯一标识(桌面端按它去重),取不到网口地址时退化成
|
||||
* 由 ANDROID_ID 派生的 12 位十六进制,保证同一台机器每次报告的值稳定。
|
||||
*/
|
||||
public final class StationIdentity {
|
||||
|
||||
/** 广播里的型号字段;桌面端只用来展示 */
|
||||
public static final String MODEL = "AndroidStation";
|
||||
|
||||
private static volatile String macCache;
|
||||
private static volatile String ipCache;
|
||||
private static volatile long ipCacheAtMs;
|
||||
|
||||
private StationIdentity() {
|
||||
}
|
||||
|
||||
/** 12 位大写十六进制,无分隔(与设备固件一致) */
|
||||
public static String mac(Context context) {
|
||||
String cached = macCache;
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
synchronized (StationIdentity.class) {
|
||||
if (macCache == null) {
|
||||
macCache = resolveMac(context);
|
||||
}
|
||||
return macCache;
|
||||
}
|
||||
}
|
||||
|
||||
private static String resolveMac(Context context) {
|
||||
String mac = hardwareAddress("eth0");
|
||||
if (mac.isEmpty()) {
|
||||
mac = hardwareAddress("wlan0");
|
||||
}
|
||||
if (mac.isEmpty()) {
|
||||
mac = anyHardwareAddress();
|
||||
}
|
||||
if (!mac.isEmpty()) {
|
||||
return mac;
|
||||
}
|
||||
return derivedMac(context);
|
||||
}
|
||||
|
||||
private static String hardwareAddress(String name) {
|
||||
try {
|
||||
NetworkInterface network = NetworkInterface.getByName(name);
|
||||
if (network == null) {
|
||||
return "";
|
||||
}
|
||||
return toHex(network.getHardwareAddress());
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String anyHardwareAddress() {
|
||||
try {
|
||||
for (NetworkInterface network : Collections.list(NetworkInterface.getNetworkInterfaces())) {
|
||||
if (network.isLoopback() || !network.isUp()) {
|
||||
continue;
|
||||
}
|
||||
String mac = toHex(network.getHardwareAddress());
|
||||
if (!mac.isEmpty()) {
|
||||
return mac;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 某些 ROM 会直接抛
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static String toHex(byte[] address) {
|
||||
if (address == null || address.length == 0) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder text = new StringBuilder(address.length * 2);
|
||||
for (byte item : address) {
|
||||
text.append(String.format(Locale.US, "%02X", item & 0xFF));
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private static String derivedMac(Context context) {
|
||||
String androidId = "";
|
||||
try {
|
||||
androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
if (androidId == null) {
|
||||
androidId = "";
|
||||
}
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("MD5");
|
||||
byte[] hash = digest.digest(androidId.getBytes("UTF-8"));
|
||||
StringBuilder text = new StringBuilder(12);
|
||||
for (int i = 0; i < 6; i++) {
|
||||
text.append(String.format(Locale.US, "%02X", hash[i] & 0xFF));
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
return "000000000000";
|
||||
}
|
||||
}
|
||||
|
||||
/** 给界面看的冒号分隔形式 */
|
||||
public static String displayMac(Context context) {
|
||||
String mac = mac(context);
|
||||
if (mac.length() != 12) {
|
||||
return mac;
|
||||
}
|
||||
StringBuilder text = new StringBuilder(17);
|
||||
for (int i = 0; i < 12; i += 2) {
|
||||
if (text.length() > 0) {
|
||||
text.append(':');
|
||||
}
|
||||
text.append(mac, i, i + 2);
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
/** 当前 IPv4 地址;没有可用网口时返回空串 */
|
||||
public static String ip() {
|
||||
String cached = ipCache;
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (cached != null && now - ipCacheAtMs < 3000) {
|
||||
return cached;
|
||||
}
|
||||
String value = resolveIp();
|
||||
ipCache = value;
|
||||
ipCacheAtMs = now;
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String resolveIp() {
|
||||
try {
|
||||
NetworkInterface eth0 = NetworkInterface.getByName("eth0");
|
||||
String value = firstIpv4(eth0);
|
||||
if (!value.isEmpty()) {
|
||||
return value;
|
||||
}
|
||||
for (NetworkInterface network : Collections.list(NetworkInterface.getNetworkInterfaces())) {
|
||||
if (network.isLoopback() || !network.isUp()) {
|
||||
continue;
|
||||
}
|
||||
value = firstIpv4(network);
|
||||
if (!value.isEmpty()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static String firstIpv4(NetworkInterface network) {
|
||||
if (network == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
List<InetAddress> addresses = Collections.list(network.getInetAddresses());
|
||||
for (InetAddress address : addresses) {
|
||||
if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
|
||||
return address.getHostAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** 设备固件格式:`0-Day 0:08:44\r\n` */
|
||||
public static String uptime() {
|
||||
long totalSeconds = SystemClock.elapsedRealtime() / 1000L;
|
||||
long days = totalSeconds / 86400L;
|
||||
long hours = (totalSeconds % 86400L) / 3600L;
|
||||
long minutes = (totalSeconds % 3600L) / 60L;
|
||||
long seconds = totalSeconds % 60L;
|
||||
return String.format(Locale.US, "%d-Day %d:%02d:%02d\r\n", days, hours, minutes, seconds);
|
||||
}
|
||||
|
||||
public static String version() {
|
||||
String version = BuildConfig.VERSION_NAME;
|
||||
return version == null || version.isEmpty() ? "1.0" : version;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,95 @@
|
||||
package com.gztbyc.scancenter.core;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
|
||||
/**
|
||||
* 设备端服务参数。
|
||||
*
|
||||
* <p>本机扮演「网口扫码设备」:对局域网广播应答发现报文,并在服务端口上监听,
|
||||
* 把 USB 扫码枪的结果推给连上来的桌面端。这里只存服务参数,<b>不再保存任何 IP/掩码/网关</b>
|
||||
* —— 设备地址由现场网络分配,改地址不属于本应用职责。
|
||||
*/
|
||||
public final class StationSettings {
|
||||
|
||||
private static final String FILE = "station_settings";
|
||||
private static final String KEY_DEVICE_NAME = "device_name";
|
||||
private static final String KEY_SERVICE_PORT = "service_port";
|
||||
private static final String KEY_DISCOVERY_PORT = "discovery_port";
|
||||
private static final String KEY_SERVICE_ENABLED = "service_enabled";
|
||||
private static final String KEY_DISCOVERY_ENABLED = "discovery_enabled";
|
||||
|
||||
/** 与桌面端 {@code ScanProtocol.TcpPort} 保持一致 */
|
||||
public static final int DEFAULT_SERVICE_PORT = 8087;
|
||||
|
||||
/** 与设备固件 / 桌面端一致 */
|
||||
public static final int DEFAULT_DISCOVERY_PORT = 48899;
|
||||
|
||||
private StationSettings() {
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
public static String deviceName(Context context) {
|
||||
String value = prefs(context).getString(KEY_DEVICE_NAME, "");
|
||||
if (value != null && !value.trim().isEmpty()) {
|
||||
return value.trim();
|
||||
}
|
||||
return defaultDeviceName();
|
||||
}
|
||||
|
||||
/** 桌面端写 HostName 时用,不再走界面 */
|
||||
public static void setDeviceName(Context context, String name) {
|
||||
String value = name == null ? "" : name.trim();
|
||||
if (value.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// 广播回复要立刻生效,commit 比 apply 更直观
|
||||
prefs(context).edit().putString(KEY_DEVICE_NAME, value).commit();
|
||||
}
|
||||
|
||||
private static String defaultDeviceName() {
|
||||
String model = Build.MODEL == null ? "" : Build.MODEL.trim();
|
||||
if (model.isEmpty() || "Android".equalsIgnoreCase(model)) {
|
||||
return "工位终端";
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
public static int servicePort(Context context) {
|
||||
return prefs(context).getInt(KEY_SERVICE_PORT, DEFAULT_SERVICE_PORT);
|
||||
}
|
||||
|
||||
public static void setServicePort(Context context, int port) {
|
||||
if (port < 1 || port > 65535) {
|
||||
return;
|
||||
}
|
||||
prefs(context).edit().putInt(KEY_SERVICE_PORT, port).commit();
|
||||
}
|
||||
|
||||
public static int discoveryPort(Context context) {
|
||||
return prefs(context).getInt(KEY_DISCOVERY_PORT, DEFAULT_DISCOVERY_PORT);
|
||||
}
|
||||
|
||||
public static boolean serviceEnabled(Context context) {
|
||||
return prefs(context).getBoolean(KEY_SERVICE_ENABLED, true);
|
||||
}
|
||||
|
||||
public static boolean discoveryEnabled(Context context) {
|
||||
return prefs(context).getBoolean(KEY_DISCOVERY_ENABLED, true);
|
||||
}
|
||||
|
||||
public static void save(Context context, String name, int servicePort, int discoveryPort,
|
||||
boolean serviceEnabled, boolean discoveryEnabled) {
|
||||
prefs(context).edit()
|
||||
.putString(KEY_DEVICE_NAME, name == null ? "" : name.trim())
|
||||
.putInt(KEY_SERVICE_PORT, servicePort)
|
||||
.putInt(KEY_DISCOVERY_PORT, discoveryPort)
|
||||
.putBoolean(KEY_SERVICE_ENABLED, serviceEnabled)
|
||||
.putBoolean(KEY_DISCOVERY_ENABLED, discoveryEnabled)
|
||||
.commit();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,365 @@
|
||||
package com.gztbyc.scancenter.core.service;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import com.gztbyc.scancenter.core.StationIdentity;
|
||||
import com.gztbyc.scancenter.core.StationSettings;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static com.gztbyc.scancenter.util.L.e;
|
||||
import static com.gztbyc.scancenter.util.L.i;
|
||||
import static com.gztbyc.scancenter.util.L.w;
|
||||
|
||||
/**
|
||||
* 设备发现应答器:扮演网口扫码设备,在 UDP 端口上响应桌面端的发现广播。
|
||||
*
|
||||
* <p>桌面端({@code Services/Scan/DiscoveryMonitor.cs})每 3 秒往
|
||||
* {@code 255.255.255.255:48899} 发一段 {@code {"Type":"EP_Tool",...}},
|
||||
* 设备把**自己的信息**回给发送方的源地址/源端口。这里必须用同一个 socket
|
||||
* 收和回,否则源端口对不上,桌面端收不到。
|
||||
*
|
||||
* <p>同时兼容桌面端的 JCMD 配置报文({@code CID 10001/10003/10005/10017}):
|
||||
* 桌面端「添加通道」时会读 SOCK 段确认 TCP 服务、把设备名写进 SYS 段。
|
||||
* <b>网络参数只读不写</b>:本机不改 IP/掩码/网关。
|
||||
*/
|
||||
public final class DiscoveryResponder {
|
||||
|
||||
public interface Callback {
|
||||
/** 桌面端通过 JCMD 写了设备名 */
|
||||
void onHostNameWritten(String name);
|
||||
|
||||
/** 桌面端要求服务端口(SOCK.LocalPort),需要本地重启扫码服务 */
|
||||
void onServicePortRequested(int port);
|
||||
}
|
||||
|
||||
private static final int CID_GET_STATE = 10001;
|
||||
private static final int CID_GET_CONFIG = 10003;
|
||||
private static final int CID_SET_CONFIG = 10005;
|
||||
private static final int CID_SAVE_FLASH = 10017;
|
||||
private static final int CID_DO_RESTART = 20003;
|
||||
|
||||
private final Context context;
|
||||
private final Callback callback;
|
||||
|
||||
private volatile DatagramSocket socket;
|
||||
private volatile Thread worker;
|
||||
private volatile boolean running;
|
||||
private volatile int port;
|
||||
private volatile String error = "";
|
||||
private volatile long lastReplyLogMs;
|
||||
|
||||
public DiscoveryResponder(Context context, Callback callback) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
public synchronized void start(int port) {
|
||||
stop();
|
||||
this.port = port;
|
||||
this.error = "";
|
||||
DatagramSocket udp = null;
|
||||
try {
|
||||
udp = new DatagramSocket(null);
|
||||
udp.setReuseAddress(true);
|
||||
udp.bind(new InetSocketAddress(port));
|
||||
udp.setSoTimeout(1000);
|
||||
}
|
||||
catch (Exception failure) {
|
||||
error = describe(failure);
|
||||
e(failure, "设备发现端口绑定失败", port);
|
||||
if (udp != null) {
|
||||
udp.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
socket = udp;
|
||||
running = true;
|
||||
worker = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
loop();
|
||||
}
|
||||
}, "station-discovery");
|
||||
worker.start();
|
||||
i("设备发现服务已启动", "UDP", port, "MAC", StationIdentity.mac(context));
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
DatagramSocket old = socket;
|
||||
socket = null;
|
||||
if (old != null) {
|
||||
try {
|
||||
old.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
Thread oldWorker = worker;
|
||||
worker = null;
|
||||
if (oldWorker != null && oldWorker != Thread.currentThread()) {
|
||||
oldWorker.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
public int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public String error() {
|
||||
return error;
|
||||
}
|
||||
|
||||
private void loop() {
|
||||
byte[] buffer = new byte[4096];
|
||||
while (running) {
|
||||
DatagramSocket udp = socket;
|
||||
if (udp == null || udp.isClosed()) {
|
||||
break;
|
||||
}
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
||||
try {
|
||||
udp.receive(packet);
|
||||
}
|
||||
catch (SocketTimeoutException timeout) {
|
||||
continue;
|
||||
}
|
||||
catch (Exception failure) {
|
||||
if (!running || udp.isClosed()) {
|
||||
break;
|
||||
}
|
||||
// 网络抖动不应该让设备从局域网里消失
|
||||
w("接收发现报文失败(继续监听)", describe(failure));
|
||||
try {
|
||||
Thread.sleep(200L);
|
||||
}
|
||||
catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
handle(udp, packet);
|
||||
}
|
||||
catch (Exception failure) {
|
||||
w("处理发现报文失败", describe(failure));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handle(DatagramSocket udp, DatagramPacket packet) throws Exception {
|
||||
if (!running) {
|
||||
return;
|
||||
}
|
||||
String text = new String(packet.getData(), packet.getOffset(), packet.getLength(),
|
||||
StandardCharsets.UTF_8).trim();
|
||||
if (!text.startsWith("{")) {
|
||||
return;
|
||||
}
|
||||
JSONObject request = new JSONObject(text);
|
||||
if ("EP_Tool".equals(request.optString("Type", ""))) {
|
||||
send(udp, packet, discoveryReply());
|
||||
// 桌面端每 3 秒探测一次,逐条打日志会把 logcat 刷满
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - lastReplyLogMs > 10_000L) {
|
||||
lastReplyLogMs = now;
|
||||
i("已应答设备发现", packet.getAddress().getHostAddress());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request.optInt("JCMD", 0) == 1) {
|
||||
handleJcmd(udp, packet, request);
|
||||
}
|
||||
}
|
||||
|
||||
/** 广播回复:字段与设备固件一致(见 docs/udp-48899-protocol.md §6) */
|
||||
private JSONObject discoveryReply() throws Exception {
|
||||
JSONObject reply = new JSONObject();
|
||||
reply.put("Agent", 0);
|
||||
reply.put("Type", StationIdentity.MODEL);
|
||||
reply.put("Version", StationIdentity.version());
|
||||
reply.put("ClientEn", 1);
|
||||
reply.put("HostName", StationSettings.deviceName(context));
|
||||
reply.put("CustomerID", StationIdentity.MODEL);
|
||||
reply.put("Uptime", StationIdentity.uptime());
|
||||
reply.put("Zone", "EPort");
|
||||
reply.put("UdpSupport", 1);
|
||||
reply.put("MAC", StationIdentity.mac(context));
|
||||
reply.put("State", "Idle");
|
||||
return reply;
|
||||
}
|
||||
|
||||
private void handleJcmd(DatagramSocket udp, DatagramPacket packet, JSONObject request)
|
||||
throws Exception {
|
||||
int cid = request.optInt("CID", 0);
|
||||
int replyCid = cid + 1;
|
||||
JSONObject reply = new JSONObject();
|
||||
reply.put("JCMD", 1);
|
||||
reply.put("CID", replyCid);
|
||||
reply.put("RC", 0);
|
||||
|
||||
switch (cid) {
|
||||
case CID_GET_STATE:
|
||||
reply.put("PL", new JSONObject().put("SOCK", sockStates()));
|
||||
break;
|
||||
|
||||
case CID_GET_CONFIG: {
|
||||
String section = requestedSection(request);
|
||||
JSONObject pl = new JSONObject();
|
||||
if ("SOCK".equalsIgnoreCase(section)) {
|
||||
pl.put("SOCK", sockEntries());
|
||||
}
|
||||
else if ("SYS".equalsIgnoreCase(section)) {
|
||||
pl.put("SYS", sysConfig());
|
||||
}
|
||||
reply.put("PL", pl);
|
||||
break;
|
||||
}
|
||||
|
||||
case CID_SET_CONFIG: {
|
||||
JSONObject pl = request.optJSONObject("PL");
|
||||
if (pl != null) {
|
||||
JSONObject sys = pl.optJSONObject("SYS");
|
||||
if (sys != null) {
|
||||
String hostName = sys.optString("HostName", "").trim();
|
||||
if (!hostName.isEmpty()) {
|
||||
StationSettings.setDeviceName(context, hostName);
|
||||
i("桌面端写入设备名", hostName);
|
||||
if (callback != null) {
|
||||
callback.onHostNameWritten(hostName);
|
||||
}
|
||||
}
|
||||
}
|
||||
JSONObject sock = pl.optJSONObject("SOCK");
|
||||
if (sock != null) {
|
||||
int localPort = sock.optInt("LocalPort", 0);
|
||||
if (localPort > 0 && localPort <= 65535
|
||||
&& localPort != StationSettings.servicePort(context)) {
|
||||
StationSettings.setServicePort(context, localPort);
|
||||
i("桌面端写入服务端口", localPort);
|
||||
if (callback != null) {
|
||||
callback.onServicePortRequested(localPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case CID_SAVE_FLASH:
|
||||
// 设置已经 commit 到 SharedPreferences,这里只需确认
|
||||
break;
|
||||
|
||||
case CID_DO_RESTART:
|
||||
// 不主动重启应用:桌面端只是确认设备收到了指令
|
||||
w("收到桌面端重启指令,设备端保持运行");
|
||||
break;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
send(udp, packet, reply);
|
||||
}
|
||||
|
||||
private static String requestedSection(JSONObject request) {
|
||||
JSONArray sections = request.optJSONArray("PL");
|
||||
if (sections != null && sections.length() > 0) {
|
||||
return sections.optString(0, "");
|
||||
}
|
||||
JSONObject object = request.optJSONObject("PL");
|
||||
if (object != null) {
|
||||
if (object.has("SOCK")) {
|
||||
return "SOCK";
|
||||
}
|
||||
if (object.has("SYS")) {
|
||||
return "SYS";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** SYS 段:只读网络参数,DHCP 固定为 1(本机不改地址) */
|
||||
private JSONObject sysConfig() throws Exception {
|
||||
String ip = StationIdentity.ip();
|
||||
JSONObject sys = new JSONObject();
|
||||
sys.put("HostName", StationSettings.deviceName(context));
|
||||
sys.put("IpAddr", ip.isEmpty() ? "0.0.0.0" : ip);
|
||||
sys.put("Mask", "0.0.0.0");
|
||||
sys.put("GateWay", "0.0.0.0");
|
||||
sys.put("Dns", "0.0.0.0");
|
||||
sys.put("DhcpEn", 1);
|
||||
sys.put("User", "");
|
||||
sys.put("Password", "");
|
||||
sys.put("Type", StationIdentity.MODEL);
|
||||
sys.put("Version", StationIdentity.version());
|
||||
sys.put("MAC", StationIdentity.mac(context));
|
||||
return sys;
|
||||
}
|
||||
|
||||
/** SOCK 段:本机只有一条「给桌面端读扫码数据」的 TCP 服务 */
|
||||
private JSONArray sockEntries() throws Exception {
|
||||
JSONObject entry = new JSONObject();
|
||||
entry.put("Name", ScanServer.SOCK_NAME);
|
||||
entry.put("Protocol", "TCP-SERVER");
|
||||
entry.put("LocalPort", StationSettings.servicePort(context));
|
||||
entry.put("maxAccept", 5);
|
||||
entry.put("Rout", "uart");
|
||||
entry.put("BufSize", 512);
|
||||
entry.put("KeepAlive", 60);
|
||||
entry.put("ConnectMode", "Always");
|
||||
entry.put("Timeout", 0);
|
||||
entry.put("Server", "");
|
||||
entry.put("ServerPort", 0);
|
||||
entry.put("HeartBeatEn", 0);
|
||||
entry.put("HeartBeatTime", 0);
|
||||
entry.put("HeartBeatCode", "");
|
||||
entry.put("RegistMode", "Disable");
|
||||
entry.put("RegistCode", "");
|
||||
entry.put("Security", "Disable");
|
||||
entry.put("SecuKey", "");
|
||||
entry.put("VcomEn", 0);
|
||||
entry.put("VpTag", "");
|
||||
return new JSONArray().put(entry);
|
||||
}
|
||||
|
||||
/** SOCK 运行状态:桌面端看门狗用它确认连接是否还活着 */
|
||||
private JSONArray sockStates() throws Exception {
|
||||
JSONObject entry = new JSONObject();
|
||||
entry.put("Name", ScanServer.SOCK_NAME);
|
||||
entry.put("SockName", ScanServer.SOCK_NAME);
|
||||
entry.put("Protocol", "TCP-SERVER");
|
||||
int clients = ScanServer.instance().clientCount();
|
||||
entry.put("State", clients > 0 ? "Connected" : "Listen");
|
||||
entry.put("ClientIP", ScanServer.instance().clientIps());
|
||||
return new JSONArray().put(entry);
|
||||
}
|
||||
|
||||
private void send(DatagramSocket udp, DatagramPacket request, JSONObject reply) throws Exception {
|
||||
byte[] data = reply.toString().getBytes(StandardCharsets.UTF_8);
|
||||
InetAddress address = request.getAddress();
|
||||
int targetPort = request.getPort();
|
||||
udp.send(new DatagramPacket(data, data.length, address, targetPort));
|
||||
}
|
||||
|
||||
private static String describe(Exception failure) {
|
||||
String message = failure.getMessage();
|
||||
return message == null ? failure.getClass().getSimpleName() : message;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,363 @@
|
||||
package com.gztbyc.scancenter.core.service;
|
||||
|
||||
import com.gztbyc.scancenter.BuildConfig;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static com.gztbyc.scancenter.util.L.e;
|
||||
import static com.gztbyc.scancenter.util.L.i;
|
||||
import static com.gztbyc.scancenter.util.L.w;
|
||||
|
||||
/**
|
||||
* 扫码数据服务:本机当服务端,桌面端连上来读取 USB 扫码枪的结果。
|
||||
*
|
||||
* <p>方向与现场网口设备一致(见桌面端 {@code ChannelConnection.cs}):
|
||||
* <b>设备监听、桌面端主动连接</b>。每收到一条扫码结果,按行(CRLF 结尾)
|
||||
* 写给所有已连接的客户端;客户端下发的扫码枪设置指令(二进制)只读取并丢弃
|
||||
* —— 本机的扫码枪是 USB HID,不需要这些串口指令。
|
||||
*/
|
||||
public final class ScanServer {
|
||||
|
||||
/** 与桌面端 {@code ScanProtocol.SockName} 一致,JCMD 里要报这个名字 */
|
||||
public static final String SOCK_NAME = "packcenter";
|
||||
|
||||
public interface Callback {
|
||||
void onClientsChanged(int count);
|
||||
}
|
||||
|
||||
private static final ScanServer INSTANCE = new ScanServer();
|
||||
|
||||
private final CopyOnWriteArrayList<Client> clients = new CopyOnWriteArrayList<Client>();
|
||||
|
||||
/**
|
||||
* 扫码结果是在主线程(按键回调)产生的,socket 写必须在后台线程做,
|
||||
* 否则 Android 直接抛 {@code NetworkOnMainThreadException}。
|
||||
* 单线程同时保证多条扫码结果按顺序发出。
|
||||
*/
|
||||
private final ExecutorService writer = Executors.newSingleThreadExecutor(new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "station-scan-write");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
});
|
||||
|
||||
private volatile ServerSocket server;
|
||||
private volatile Thread acceptThread;
|
||||
private volatile boolean running;
|
||||
private volatile int port;
|
||||
private volatile String error = "";
|
||||
private volatile Callback callback;
|
||||
|
||||
/** 只在写线程里访问:前几条打印排队+写入耗时,之后不再打日志 */
|
||||
private int debugPushes;
|
||||
private int idleScans;
|
||||
|
||||
private ScanServer() {
|
||||
}
|
||||
|
||||
public static ScanServer instance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public void setCallback(Callback callback) {
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
public synchronized void start(int port) {
|
||||
stop();
|
||||
this.port = port;
|
||||
this.error = "";
|
||||
ServerSocket socket = null;
|
||||
try {
|
||||
socket = new ServerSocket();
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(port), 8);
|
||||
}
|
||||
catch (Exception failure) {
|
||||
error = describe(failure);
|
||||
e(failure, "扫码服务端口绑定失败", port);
|
||||
if (socket != null) {
|
||||
try {
|
||||
socket.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
server = socket;
|
||||
running = true;
|
||||
acceptThread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
acceptLoop();
|
||||
}
|
||||
}, "station-scan-accept");
|
||||
acceptThread.start();
|
||||
i("扫码服务已启动", "TCP", port);
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
ServerSocket old = server;
|
||||
server = null;
|
||||
if (old != null) {
|
||||
try {
|
||||
old.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
for (Client client : clients) {
|
||||
client.close();
|
||||
}
|
||||
clients.clear();
|
||||
Thread oldAccept = acceptThread;
|
||||
acceptThread = null;
|
||||
if (oldAccept != null && oldAccept != Thread.currentThread()) {
|
||||
oldAccept.interrupt();
|
||||
}
|
||||
notifyClients();
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
}
|
||||
|
||||
public int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public String error() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public int clientCount() {
|
||||
return clients.size();
|
||||
}
|
||||
|
||||
/** 设备侧 SOCK.ClientIP 用;多个客户端时逗号分隔 */
|
||||
public String clientIps() {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (Client client : clients) {
|
||||
if (client.remoteIp.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (text.length() > 0) {
|
||||
text.append(',');
|
||||
}
|
||||
text.append(client.remoteIp);
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一条扫码结果推给所有客户端。
|
||||
*
|
||||
* <p>⚠️ <b>不去重</b>:重复条码也照发,连续扫描的重复帧由桌面端自己判断。
|
||||
* 这里只做两件事——复制成字节、丢给后台写线程,调用方(按键回调)立即返回。
|
||||
*/
|
||||
public void push(String barcode) {
|
||||
if (barcode == null || barcode.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final String code = barcode;
|
||||
final long queuedAtMs = System.currentTimeMillis();
|
||||
final byte[] data = (code + "\r\n").getBytes(StandardCharsets.UTF_8);
|
||||
writer.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
int sent = 0;
|
||||
for (Client client : clients) {
|
||||
if (client.write(data)) {
|
||||
sent++;
|
||||
}
|
||||
else {
|
||||
remove(client);
|
||||
}
|
||||
}
|
||||
if (sent == 0) {
|
||||
// 没有桌面端连接:低频提示,避免每条都刷日志
|
||||
if (++idleScans % 20 == 0) {
|
||||
i("扫码结果没有桌面端连接", code);
|
||||
}
|
||||
}
|
||||
else if (BuildConfig.DEBUG && debugPushes < 5) {
|
||||
debugPushes++;
|
||||
i("扫码推送完成", code, "客户端", sent,
|
||||
"排队+写", (System.currentTimeMillis() - queuedAtMs) + "ms");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void acceptLoop() {
|
||||
while (running) {
|
||||
ServerSocket listener = server;
|
||||
if (listener == null || listener.isClosed()) {
|
||||
break;
|
||||
}
|
||||
Socket accepted = null;
|
||||
try {
|
||||
accepted = listener.accept();
|
||||
Client client = new Client(accepted);
|
||||
clients.add(client);
|
||||
i("桌面端已连接扫码服务", client.remoteIp, "当前", clients.size());
|
||||
notifyClients();
|
||||
client.startReader();
|
||||
}
|
||||
catch (Exception failure) {
|
||||
if (accepted != null) {
|
||||
try {
|
||||
accepted.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
if (!running || listener.isClosed()) {
|
||||
break;
|
||||
}
|
||||
// 单个连接(比如客户端刚连上就断)不应把整个监听线程结束掉
|
||||
w("接受扫码服务连接失败(继续监听)", describe(failure));
|
||||
try {
|
||||
Thread.sleep(200L);
|
||||
}
|
||||
catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void remove(Client client) {
|
||||
if (client.closed.get()) {
|
||||
return;
|
||||
}
|
||||
client.close();
|
||||
if (clients.remove(client)) {
|
||||
i("桌面端已断开扫码服务", client.remoteIp, "当前", clients.size());
|
||||
notifyClients();
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyClients() {
|
||||
Callback current = callback;
|
||||
if (current != null) {
|
||||
current.onClientsChanged(clients.size());
|
||||
}
|
||||
}
|
||||
|
||||
private static String describe(Exception failure) {
|
||||
String message = failure.getMessage();
|
||||
return message == null ? failure.getClass().getSimpleName() : message;
|
||||
}
|
||||
|
||||
/** 双栈 socket 可能把 IPv4 给成 `::ffff:192.168.1.5`,要归一化后才能和桌面端对账 */
|
||||
private static String normalizeIp(java.net.InetAddress address) {
|
||||
if (address == null) {
|
||||
return "";
|
||||
}
|
||||
String text = address.getHostAddress();
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
if (text.startsWith("::ffff:")) {
|
||||
text = text.substring(7);
|
||||
}
|
||||
int scope = text.indexOf('%');
|
||||
return scope > 0 ? text.substring(0, scope) : text;
|
||||
}
|
||||
|
||||
private final class Client implements Runnable {
|
||||
|
||||
final Socket socket;
|
||||
final String remoteIp;
|
||||
final AtomicBoolean closed = new AtomicBoolean(false);
|
||||
final InputStream input;
|
||||
final OutputStream output;
|
||||
Thread reader;
|
||||
|
||||
Client(Socket socket) throws Exception {
|
||||
this.socket = socket;
|
||||
this.socket.setTcpNoDelay(true);
|
||||
this.remoteIp = normalizeIp(socket.getInetAddress());
|
||||
this.input = socket.getInputStream();
|
||||
this.output = socket.getOutputStream();
|
||||
}
|
||||
|
||||
void startReader() {
|
||||
reader = new Thread(this, "station-scan-client");
|
||||
reader.start();
|
||||
}
|
||||
|
||||
/** 串行写,避免多条扫码结果在同一个 socket 上交错 */
|
||||
synchronized boolean write(byte[] data) {
|
||||
if (closed.get()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
output.write(data);
|
||||
output.flush();
|
||||
return true;
|
||||
}
|
||||
catch (Exception failure) {
|
||||
w("推送扫码结果失败", remoteIp, describe(failure));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
byte[] buffer = new byte[512];
|
||||
boolean logged = false;
|
||||
try {
|
||||
while (running && !closed.get()) {
|
||||
int read = input.read(buffer);
|
||||
if (read < 0) {
|
||||
break;
|
||||
}
|
||||
if (!logged) {
|
||||
logged = true;
|
||||
// 桌面端连上后会下发扫码枪设置(串口指令),本机是 USB HID,忽略
|
||||
i("已忽略桌面端下发的扫码枪设置指令", remoteIp, read + " 字节");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 断开就是断开,不必刷错误
|
||||
}
|
||||
finally {
|
||||
remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
void close() {
|
||||
if (!closed.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
socket.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,254 @@
|
||||
package com.gztbyc.scancenter.core.service;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import com.gztbyc.scancenter.core.StationSettings;
|
||||
import com.gztbyc.scancenter.core.speech.BarcodeSpeaker;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* 设备端服务总入口:发现应答 + 扫码推送。
|
||||
*
|
||||
* <p>进程级单例,随 {@code App#onCreate} 启动;页面重建不影响服务。
|
||||
*/
|
||||
public final class StationService {
|
||||
|
||||
public interface Listener {
|
||||
/** 服务状态(启停/客户端数量/设备名)有变化 */
|
||||
void onStateChanged();
|
||||
}
|
||||
|
||||
public static final class ScanEntry {
|
||||
public final String code;
|
||||
public final long atMs;
|
||||
|
||||
ScanEntry(String code, long atMs) {
|
||||
this.code = code;
|
||||
this.atMs = atMs;
|
||||
}
|
||||
}
|
||||
|
||||
private static final int MAX_HISTORY = 30;
|
||||
|
||||
private static final StationService INSTANCE = new StationService();
|
||||
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
|
||||
private final ArrayDeque<ScanEntry> history = new ArrayDeque<ScanEntry>();
|
||||
|
||||
private Context context;
|
||||
private DiscoveryResponder discovery;
|
||||
private boolean running;
|
||||
|
||||
private String lastCode = "";
|
||||
private long lastScanAt;
|
||||
private long totalScans;
|
||||
|
||||
private StationService() {
|
||||
}
|
||||
|
||||
public static StationService instance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public synchronized void start(Context context) {
|
||||
if (running) {
|
||||
return;
|
||||
}
|
||||
this.context = context.getApplicationContext();
|
||||
running = true;
|
||||
startInternal();
|
||||
notifyState();
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
running = false;
|
||||
stopInternal();
|
||||
notifyState();
|
||||
}
|
||||
|
||||
/** 设置变更后整体重启(端口/开关可能都变了) */
|
||||
public synchronized void restart() {
|
||||
stopInternal();
|
||||
if (running) {
|
||||
startInternal();
|
||||
}
|
||||
notifyState();
|
||||
}
|
||||
|
||||
private void startInternal() {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
ScanServer.instance().setCallback(new ScanServer.Callback() {
|
||||
@Override
|
||||
public void onClientsChanged(int count) {
|
||||
notifyState();
|
||||
}
|
||||
});
|
||||
|
||||
if (StationSettings.discoveryEnabled(context)) {
|
||||
discovery = new DiscoveryResponder(context, new DiscoveryResponder.Callback() {
|
||||
@Override
|
||||
public void onHostNameWritten(String name) {
|
||||
notifyState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServicePortRequested(int port) {
|
||||
mainHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
restartScanServer();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
discovery.start(StationSettings.discoveryPort(context));
|
||||
}
|
||||
|
||||
if (StationSettings.serviceEnabled(context)) {
|
||||
ScanServer.instance().start(StationSettings.servicePort(context));
|
||||
}
|
||||
}
|
||||
|
||||
private void stopInternal() {
|
||||
if (discovery != null) {
|
||||
discovery.stop();
|
||||
discovery = null;
|
||||
}
|
||||
ScanServer.instance().stop();
|
||||
}
|
||||
|
||||
private synchronized void restartScanServer() {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
ScanServer.instance().stop();
|
||||
if (StationSettings.serviceEnabled(context)) {
|
||||
ScanServer.instance().start(StationSettings.servicePort(context));
|
||||
}
|
||||
notifyState();
|
||||
}
|
||||
|
||||
public void addListener(Listener listener) {
|
||||
if (listener != null && !listeners.contains(listener)) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeListener(Listener listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到一条扫码结果:记入历史并推给所有桌面端连接。
|
||||
*
|
||||
* <p>无论服务是否启用都记账 —— 现场排查时「扫了但没推出去」比「没扫上」更难分辨。
|
||||
*/
|
||||
public void pushBarcode(String code) {
|
||||
if (code == null || code.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
synchronized (history) {
|
||||
lastCode = code;
|
||||
lastScanAt = now;
|
||||
totalScans++;
|
||||
history.addFirst(new ScanEntry(code, now));
|
||||
while (history.size() > MAX_HISTORY) {
|
||||
history.removeLast();
|
||||
}
|
||||
}
|
||||
// 热路径只入队,不写日志、不通知 UI:桌面端连接与否都由后台写线程处理
|
||||
ScanServer.instance().push(code);
|
||||
// 语音播报同样在独立线程,主线程只做一次很轻的判重/入队
|
||||
BarcodeSpeaker.instance().announce(code);
|
||||
}
|
||||
|
||||
public void clearHistory() {
|
||||
synchronized (history) {
|
||||
history.clear();
|
||||
lastCode = "";
|
||||
lastScanAt = 0L;
|
||||
totalScans = 0L;
|
||||
}
|
||||
notifyState();
|
||||
}
|
||||
|
||||
public String lastCode() {
|
||||
synchronized (history) {
|
||||
return lastCode;
|
||||
}
|
||||
}
|
||||
|
||||
public long lastScanAt() {
|
||||
synchronized (history) {
|
||||
return lastScanAt;
|
||||
}
|
||||
}
|
||||
|
||||
public long totalScans() {
|
||||
synchronized (history) {
|
||||
return totalScans;
|
||||
}
|
||||
}
|
||||
|
||||
public List<ScanEntry> history() {
|
||||
synchronized (history) {
|
||||
return new ArrayList<ScanEntry>(history);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isDiscoveryRunning() {
|
||||
DiscoveryResponder current = discovery;
|
||||
return current != null && current.isRunning();
|
||||
}
|
||||
|
||||
public String discoveryError() {
|
||||
DiscoveryResponder current = discovery;
|
||||
return current == null ? "" : current.error();
|
||||
}
|
||||
|
||||
public int discoveryPort() {
|
||||
return context == null ? StationSettings.DEFAULT_DISCOVERY_PORT
|
||||
: StationSettings.discoveryPort(context);
|
||||
}
|
||||
|
||||
public boolean isServiceRunning() {
|
||||
return ScanServer.instance().isRunning();
|
||||
}
|
||||
|
||||
public String serviceError() {
|
||||
return ScanServer.instance().error();
|
||||
}
|
||||
|
||||
public int servicePort() {
|
||||
return ScanServer.instance().port() > 0 ? ScanServer.instance().port()
|
||||
: (context == null ? StationSettings.DEFAULT_SERVICE_PORT
|
||||
: StationSettings.servicePort(context));
|
||||
}
|
||||
|
||||
public int clientCount() {
|
||||
return ScanServer.instance().clientCount();
|
||||
}
|
||||
|
||||
private void notifyState() {
|
||||
mainHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
for (Listener listener : listeners) {
|
||||
listener.onStateChanged();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,555 @@
|
||||
package com.gztbyc.scancenter.core.speech;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.AudioManager;
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import com.gztbyc.scancenter.R;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
import static com.gztbyc.scancenter.util.L.e;
|
||||
import static com.gztbyc.scancenter.util.L.i;
|
||||
import static com.gztbyc.scancenter.util.L.w;
|
||||
|
||||
/**
|
||||
* 离线语音播报:播「条码后四位 + 开始打包」。
|
||||
*
|
||||
* <p>设备上只有 PicoTts 且没有中文语音数据,所以运行时不用 TextToSpeech:
|
||||
* 事先用 `tools/fetch-voice-seeds.ps1` 从现场语音服务把 0-9、A-Z、「开始打包」
|
||||
* 一次性抓成 44.1kHz/立体声/16-bit PCM,放在 {@code res/raw}。运行时只读本地资源,
|
||||
* 断网也能播报。
|
||||
*
|
||||
* <p>播放用系统 {@link MediaPlayer} 读一个临时拼接的 WAV:这台 rk3288 的
|
||||
* AudioTrack 直接初始化会失败,MediaPlayer 由音频框架负责重采样/路由,兼容性更好。
|
||||
*
|
||||
* <p>播报与扫码上报互不阻塞:拼 PCM、写临时 WAV、起播都在 {@code station-speech} 线程,
|
||||
* 主线程只做一个「入队」。连续扫同一个码时 {@link #REPEAT_QUIET_MS} 内不重复播报;
|
||||
* 换了条码会立即停掉上一句、播最新的。
|
||||
*/
|
||||
public final class BarcodeSpeaker {
|
||||
|
||||
/** 与设备 AudioFlinger 的输出线程一致(实测 rk3288:44100Hz / 立体声 / pcm16) */
|
||||
private static final int SAMPLE_RATE = 44100;
|
||||
private static final int CHANNELS = 2;
|
||||
private static final int BITS_PER_SAMPLE = 16;
|
||||
private static final int BYTES_PER_FRAME = CHANNELS * BITS_PER_SAMPLE / 8;
|
||||
|
||||
/** 数字之间的停顿 */
|
||||
private static final int TOKEN_GAP_MS = 20;
|
||||
|
||||
/** 后四位与「开始打包」之间的停顿 */
|
||||
private static final int PHRASE_GAP_MS = 80;
|
||||
|
||||
/** 同一个条码在这个时间内不重复播报(连续扫描的重复帧) */
|
||||
private static final long REPEAT_QUIET_MS = 2500L;
|
||||
|
||||
/** 启动后延迟多久播欢迎语(等 Activity/服务都就绪) */
|
||||
private static final long WELCOME_DELAY_MS = 1200L;
|
||||
|
||||
private static final int[] DIGIT_RES = {
|
||||
R.raw.voice_0, R.raw.voice_1, R.raw.voice_2, R.raw.voice_3, R.raw.voice_4,
|
||||
R.raw.voice_5, R.raw.voice_6, R.raw.voice_7, R.raw.voice_8, R.raw.voice_9,
|
||||
};
|
||||
|
||||
private static final int[] LETTER_RES = {
|
||||
R.raw.voice_a, R.raw.voice_b, R.raw.voice_c, R.raw.voice_d, R.raw.voice_e,
|
||||
R.raw.voice_f, R.raw.voice_g, R.raw.voice_h, R.raw.voice_i, R.raw.voice_j,
|
||||
R.raw.voice_k, R.raw.voice_l, R.raw.voice_m, R.raw.voice_n, R.raw.voice_o,
|
||||
R.raw.voice_p, R.raw.voice_q, R.raw.voice_r, R.raw.voice_s, R.raw.voice_t,
|
||||
R.raw.voice_u, R.raw.voice_v, R.raw.voice_w, R.raw.voice_x, R.raw.voice_y,
|
||||
R.raw.voice_z,
|
||||
};
|
||||
|
||||
private static final BarcodeSpeaker INSTANCE = new BarcodeSpeaker();
|
||||
|
||||
private final Object lock = new Object();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private final Map<Integer, byte[]> pcmCache = new HashMap<Integer, byte[]>();
|
||||
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "station-speech");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
});
|
||||
|
||||
private volatile Context context;
|
||||
private MediaPlayer player;
|
||||
private File playerFile;
|
||||
private int generation;
|
||||
private String lastCode = "";
|
||||
private long lastAnnouncedAt;
|
||||
private boolean cacheCleaned;
|
||||
private boolean welcomeScheduled;
|
||||
|
||||
private BarcodeSpeaker() {
|
||||
}
|
||||
|
||||
public static BarcodeSpeaker instance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
/** 进程启动时调用;重复调用安全(会重新确认一次音量) */
|
||||
public void start(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
synchronized (lock) {
|
||||
if (!cacheCleaned) {
|
||||
cacheCleaned = true;
|
||||
cleanupCache();
|
||||
}
|
||||
}
|
||||
maximizeVolume(this.context);
|
||||
scheduleWelcome();
|
||||
}
|
||||
|
||||
/** 进程启动后播一次欢迎语;如果操作员已经先扫码,就让位给扫码播报 */
|
||||
private void scheduleWelcome() {
|
||||
if (welcomeScheduled) {
|
||||
return;
|
||||
}
|
||||
welcomeScheduled = true;
|
||||
mainHandler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (lock) {
|
||||
if (!lastCode.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
worker.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
byte[] pcm = loadPcm(R.raw.voice_welcome);
|
||||
if (pcm.length == 0) {
|
||||
w("欢迎语音种子缺失");
|
||||
return;
|
||||
}
|
||||
playPcm(pcm, "welcome");
|
||||
}
|
||||
});
|
||||
}
|
||||
}, WELCOME_DELAY_MS);
|
||||
}
|
||||
|
||||
/** 把媒体/系统音量开到最大(设备启动后默认满音量) */
|
||||
public static void maximizeVolume(Context context) {
|
||||
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (audio == null) {
|
||||
w("拿不到 AudioManager,跳过音量设置");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 某些 ROM 在固定音量策略下会拒绝,继续尝试直接写音量
|
||||
}
|
||||
|
||||
int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
|
||||
int before = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
|
||||
try {
|
||||
audio.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);
|
||||
}
|
||||
catch (Exception failure) {
|
||||
w("设置媒体音量失败", describe(failure));
|
||||
}
|
||||
try {
|
||||
int systemMax = audio.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
|
||||
audio.setStreamVolume(AudioManager.STREAM_SYSTEM, systemMax, 0);
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 系统音量不是必需的,失败不影响播报
|
||||
}
|
||||
i("音量已设为最大", before, "->", max);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到一条扫码结果后调用。
|
||||
*
|
||||
* <p>只做很轻的判重和入队;拼 PCM、写 WAV、起播都在 {@code station-speech} 线程。
|
||||
*/
|
||||
public void announce(String code) {
|
||||
Context ctx = context;
|
||||
if (ctx == null || code == null || code.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final String tail = lastAlnum(code, 4);
|
||||
if (tail.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
synchronized (lock) {
|
||||
if (code.equals(lastCode) && now - lastAnnouncedAt < REPEAT_QUIET_MS) {
|
||||
return;
|
||||
}
|
||||
lastCode = code;
|
||||
lastAnnouncedAt = now;
|
||||
}
|
||||
|
||||
worker.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
byte[] pcm = buildPcm(tail);
|
||||
if (pcm.length == 0) {
|
||||
w("没有可用的语音种子", tail);
|
||||
return;
|
||||
}
|
||||
playPcm(pcm, tail);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void playPcm(byte[] pcm, String label) {
|
||||
Context ctx = context;
|
||||
if (ctx == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
File file = null;
|
||||
MediaPlayer created = null;
|
||||
try {
|
||||
// 文件 I/O 和 prepare 都在锁外做:扫码主线程绝不等待语音准备工作
|
||||
file = File.createTempFile("voice-", ".wav", ctx.getCacheDir());
|
||||
writeWav(file, pcm);
|
||||
|
||||
created = new MediaPlayer();
|
||||
created.setAudioAttributes(new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||
.build());
|
||||
created.setDataSource(file.getAbsolutePath());
|
||||
created.prepare();
|
||||
|
||||
final int myGeneration;
|
||||
MediaPlayer oldPlayer;
|
||||
File oldFile;
|
||||
synchronized (lock) {
|
||||
myGeneration = ++generation;
|
||||
oldPlayer = player;
|
||||
oldFile = playerFile;
|
||||
player = created;
|
||||
playerFile = file;
|
||||
created.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
|
||||
@Override
|
||||
public void onCompletion(MediaPlayer mediaPlayer) {
|
||||
releaseIfCurrent(myGeneration);
|
||||
}
|
||||
});
|
||||
created.setOnErrorListener(new MediaPlayer.OnErrorListener() {
|
||||
@Override
|
||||
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
|
||||
w("MediaPlayer 播报错误", label, what, extra);
|
||||
releaseIfCurrent(myGeneration);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
releasePlayer(oldPlayer, oldFile);
|
||||
created.start();
|
||||
|
||||
long durationMs = pcm.length * 1000L / (SAMPLE_RATE * BYTES_PER_FRAME);
|
||||
i("语音播报", label, durationMs + "ms");
|
||||
}
|
||||
catch (Exception failure) {
|
||||
e(failure, "语音播报失败", label);
|
||||
synchronized (lock) {
|
||||
if (player == created) {
|
||||
player = null;
|
||||
playerFile = null;
|
||||
}
|
||||
}
|
||||
if (created != null) {
|
||||
try {
|
||||
created.release();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
if (file != null) {
|
||||
// 没交给 MediaPlayer 的文件要清掉
|
||||
try {
|
||||
file.delete();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseIfCurrent(int expectedGeneration) {
|
||||
MediaPlayer target;
|
||||
File file;
|
||||
synchronized (lock) {
|
||||
if (expectedGeneration != generation) {
|
||||
return;
|
||||
}
|
||||
target = player;
|
||||
file = playerFile;
|
||||
player = null;
|
||||
playerFile = null;
|
||||
}
|
||||
releasePlayer(target, file);
|
||||
}
|
||||
|
||||
private static void releasePlayer(MediaPlayer target, File file) {
|
||||
if (target != null) {
|
||||
try {
|
||||
target.stop();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 已经播完 / 还没起播
|
||||
}
|
||||
try {
|
||||
target.release();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
if (file != null) {
|
||||
try {
|
||||
file.delete();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupCache() {
|
||||
try {
|
||||
Context ctx = context;
|
||||
if (ctx == null) {
|
||||
return;
|
||||
}
|
||||
File[] files = ctx.getCacheDir().listFiles();
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
for (File file : files) {
|
||||
String name = file.getName();
|
||||
if (name.startsWith("voice-") && name.endsWith(".wav")) {
|
||||
try {
|
||||
file.delete();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 缓存清理失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] buildPcm(String tail) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int tokens = 0;
|
||||
for (int index = 0; index < tail.length(); index++) {
|
||||
int resource = resourceFor(tail.charAt(index));
|
||||
if (resource == 0) {
|
||||
continue;
|
||||
}
|
||||
byte[] pcm = loadPcm(resource);
|
||||
if (pcm.length == 0) {
|
||||
continue;
|
||||
}
|
||||
if (tokens > 0) {
|
||||
writeSilence(out, TOKEN_GAP_MS);
|
||||
}
|
||||
out.write(pcm, 0, pcm.length);
|
||||
tokens++;
|
||||
}
|
||||
if (tokens == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
writeSilence(out, PHRASE_GAP_MS);
|
||||
byte[] phrase = loadPcm(R.raw.voice_start_pack);
|
||||
if (phrase.length > 0) {
|
||||
out.write(phrase, 0, phrase.length);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] loadPcm(int resource) {
|
||||
synchronized (pcmCache) {
|
||||
byte[] cached = pcmCache.get(resource);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
byte[] pcm = readWavPcm(resource);
|
||||
pcmCache.put(resource, pcm);
|
||||
return pcm;
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 res/raw 的 16-bit PCM WAV 里取出 data 段(文件已由脚本统一成 44.1k/stereo/16bit) */
|
||||
private byte[] readWavPcm(int resource) {
|
||||
Context ctx = context;
|
||||
if (ctx == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
InputStream input = null;
|
||||
try {
|
||||
input = ctx.getResources().openRawResource(resource);
|
||||
byte[] all = readAll(input);
|
||||
if (all.length < 44) {
|
||||
return new byte[0];
|
||||
}
|
||||
int position = 12; // 跳过 RIFF + size + WAVE
|
||||
while (position + 8 <= all.length) {
|
||||
String id = new String(all, position, 4, StandardCharsets.US_ASCII);
|
||||
int size = littleEndianInt(all, position + 4);
|
||||
int dataStart = position + 8;
|
||||
if (size < 0 || dataStart + size > all.length) {
|
||||
size = all.length - dataStart;
|
||||
}
|
||||
if ("data".equals(id)) {
|
||||
byte[] pcm = new byte[size];
|
||||
System.arraycopy(all, dataStart, pcm, 0, size);
|
||||
return pcm;
|
||||
}
|
||||
position = dataStart + size + (size & 1);
|
||||
}
|
||||
}
|
||||
catch (Exception failure) {
|
||||
w("读语音种子失败", resource, describe(failure));
|
||||
}
|
||||
finally {
|
||||
if (input != null) {
|
||||
try {
|
||||
input.close();
|
||||
}
|
||||
catch (Exception ignored) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
private static void writeWav(File file, byte[] pcm) throws Exception {
|
||||
FileOutputStream out = new FileOutputStream(file);
|
||||
try {
|
||||
out.write(wavHeader(pcm.length));
|
||||
out.write(pcm);
|
||||
out.flush();
|
||||
}
|
||||
finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] wavHeader(int dataLength) {
|
||||
byte[] header = new byte[44];
|
||||
putAscii(header, 0, "RIFF");
|
||||
putInt(header, 4, 36 + dataLength);
|
||||
putAscii(header, 8, "WAVE");
|
||||
putAscii(header, 12, "fmt ");
|
||||
putInt(header, 16, 16);
|
||||
putShort(header, 20, 1); // PCM
|
||||
putShort(header, 22, CHANNELS);
|
||||
putInt(header, 24, SAMPLE_RATE);
|
||||
putInt(header, 28, SAMPLE_RATE * BYTES_PER_FRAME);
|
||||
putShort(header, 32, BYTES_PER_FRAME);
|
||||
putShort(header, 34, BITS_PER_SAMPLE);
|
||||
putAscii(header, 36, "data");
|
||||
putInt(header, 40, dataLength);
|
||||
return header;
|
||||
}
|
||||
|
||||
private static void putAscii(byte[] target, int offset, String value) {
|
||||
for (int index = 0; index < value.length(); index++) {
|
||||
target[offset + index] = (byte) value.charAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
private static void putInt(byte[] target, int offset, int value) {
|
||||
target[offset] = (byte) value;
|
||||
target[offset + 1] = (byte) (value >>> 8);
|
||||
target[offset + 2] = (byte) (value >>> 16);
|
||||
target[offset + 3] = (byte) (value >>> 24);
|
||||
}
|
||||
|
||||
private static void putShort(byte[] target, int offset, int value) {
|
||||
target[offset] = (byte) value;
|
||||
target[offset + 1] = (byte) (value >>> 8);
|
||||
}
|
||||
|
||||
private static byte[] readAll(InputStream input) throws Exception {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] chunk = new byte[4096];
|
||||
int read;
|
||||
while ((read = input.read(chunk)) > 0) {
|
||||
buffer.write(chunk, 0, read);
|
||||
}
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
private static int littleEndianInt(byte[] data, int offset) {
|
||||
return (data[offset] & 0xFF)
|
||||
| ((data[offset + 1] & 0xFF) << 8)
|
||||
| ((data[offset + 2] & 0xFF) << 16)
|
||||
| ((data[offset + 3] & 0xFF) << 24);
|
||||
}
|
||||
|
||||
private static void writeSilence(ByteArrayOutputStream out, int milliseconds) {
|
||||
int bytes = SAMPLE_RATE * milliseconds / 1000 * BYTES_PER_FRAME;
|
||||
if (bytes <= 0) {
|
||||
return;
|
||||
}
|
||||
byte[] silence = new byte[bytes];
|
||||
out.write(silence, 0, bytes);
|
||||
}
|
||||
|
||||
private static int resourceFor(char value) {
|
||||
char upper = Character.toUpperCase(value);
|
||||
if (upper >= '0' && upper <= '9') {
|
||||
return DIGIT_RES[upper - '0'];
|
||||
}
|
||||
if (upper >= 'A' && upper <= 'Z') {
|
||||
return LETTER_RES[upper - 'A'];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** 取条码末尾的 count 个字母/数字,保持原顺序 */
|
||||
private static String lastAlnum(String code, int count) {
|
||||
StringBuilder tail = new StringBuilder(count);
|
||||
for (int index = code.length() - 1; index >= 0 && tail.length() < count; index--) {
|
||||
char value = code.charAt(index);
|
||||
if ((value >= '0' && value <= '9')
|
||||
|| (value >= 'A' && value <= 'Z')
|
||||
|| (value >= 'a' && value <= 'z')) {
|
||||
tail.append(Character.toUpperCase(value));
|
||||
}
|
||||
}
|
||||
return tail.reverse().toString();
|
||||
}
|
||||
|
||||
private static String describe(Exception failure) {
|
||||
String message = failure.getMessage();
|
||||
return message == null ? failure.getClass().getSimpleName() : message;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,59 @@
|
||||
package com.gztbyc.scancenter.receiver;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import com.gztbyc.scancenter.MainActivity;
|
||||
|
||||
import static com.gztbyc.scancenter.util.L.e;
|
||||
import static com.gztbyc.scancenter.util.L.i;
|
||||
import static com.gztbyc.scancenter.util.L.w;
|
||||
|
||||
/**
|
||||
* 开机自启动:工位设备断电重启后自动进入设备端主界面。
|
||||
*
|
||||
* <p>应用本体是服务型终端,主界面只是状态展示,所以直接拉起 {@link MainActivity}。
|
||||
*
|
||||
* <p>为什么可以直接 startActivity:
|
||||
* <ul>
|
||||
* <li>Android 10 起限制「后台启动 Activity」,但只对 <b>targetSdk ≥ 29</b> 生效,
|
||||
* 本工程 targetSdk 28,不在限制范围内;</li>
|
||||
* <li>{@code BOOT_COMPLETED} 在 Android 8.0+ 的隐式广播限制<b>豁免名单</b>里,
|
||||
* 所以清单里静态注册仍然有效。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>⚠️ 应用<b>新装且从未启动过</b>时处于 stopped 状态,系统不会给它发开机广播,
|
||||
* 必须手动启动一次之后才会生效。这是 Android 的既定行为,不是 bug。
|
||||
*/
|
||||
public class BootReceiver extends BroadcastReceiver {
|
||||
|
||||
/** 部分国产 ROM(HTC / 一些定制系统)用这个代替标准的 BOOT_COMPLETED */
|
||||
private static final String ACTION_QUICKBOOT = "android.intent.action.QUICKBOOT_POWERON";
|
||||
private static final String ACTION_HTC_QUICKBOOT = "com.htc.intent.action.QUICKBOOT_POWERON";
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String action = intent == null ? "" : intent.getAction();
|
||||
|
||||
if (!Intent.ACTION_BOOT_COMPLETED.equals(action)
|
||||
&& !ACTION_QUICKBOOT.equals(action)
|
||||
&& !ACTION_HTC_QUICKBOOT.equals(action)) {
|
||||
return;
|
||||
}
|
||||
|
||||
i("收到开机广播,准备自启动", action);
|
||||
try {
|
||||
Intent launch = new Intent(context, MainActivity.class);
|
||||
// 从 Receiver 启动 Activity 必须带 NEW_TASK,否则直接抛异常
|
||||
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
context.startActivity(launch);
|
||||
i("开机自启动已拉起设备端主界面");
|
||||
}
|
||||
catch (Exception error) {
|
||||
// 自启动失败不该让进程崩掉:用户手动点图标仍然能进
|
||||
w("开机自启动失败,需要手动启动应用");
|
||||
e("开机自启动异常", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,168 @@
|
||||
package com.gztbyc.scancenter.util;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.gztbyc.scancenter.BuildConfig;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 轻量日志工具:静态导入之后就能像 console.log 一样一次打印多个参数。
|
||||
*
|
||||
* <pre>
|
||||
* import static com.gztbyc.scancenter.util.L.*;
|
||||
*
|
||||
* log("扫码结果", code, "耗时", ms);
|
||||
* e(exception, "请求失败", url);
|
||||
* </pre>
|
||||
*
|
||||
* <p>设计要点:
|
||||
* <ul>
|
||||
* <li>固定 tag({@link #TAG}),长度不超过 23,避免 API 24 以下被系统截断;
|
||||
* 类名/方法名/行号放在消息里,便于定位的同时仍能用一个 tag 过滤全部日志。</li>
|
||||
* <li>单条日志超过 {@link #MAX_CHUNK} 时自动分段,规避 logcat 约 4000 字节的截断。</li>
|
||||
* <li>release 包默认不输出:仅当 {@code BuildConfig.DEBUG} 为真,
|
||||
* 或运行期用 {@code adb shell setprop log.tag.AndroidStation DEBUG} 显式打开。
|
||||
* 这样排查线上包时无需重新编译。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class L {
|
||||
|
||||
/** 所有日志统一使用这一个 tag,方便 adb logcat 过滤 */
|
||||
public static final String TAG = "AndroidStation";
|
||||
|
||||
/** logcat 单条约 4000 字节,留出前缀余量后按 3000 分段 */
|
||||
private static final int MAX_CHUNK = 3000;
|
||||
|
||||
private L() {
|
||||
// 工具类,不允许实例化
|
||||
}
|
||||
|
||||
// ---------------- console.log 风格 ----------------
|
||||
|
||||
/** 等价于 console.log(...) */
|
||||
public static void log(Object... args) {
|
||||
d(args);
|
||||
}
|
||||
|
||||
public static void d(Object... args) {
|
||||
if (!isEnabled(Log.DEBUG)) {
|
||||
return;
|
||||
}
|
||||
write(Log.DEBUG, null, build(args));
|
||||
}
|
||||
|
||||
public static void i(Object... args) {
|
||||
if (!isEnabled(Log.INFO)) {
|
||||
return;
|
||||
}
|
||||
write(Log.INFO, null, build(args));
|
||||
}
|
||||
|
||||
public static void w(Object... args) {
|
||||
if (!isEnabled(Log.WARN)) {
|
||||
return;
|
||||
}
|
||||
write(Log.WARN, null, build(args));
|
||||
}
|
||||
|
||||
public static void e(Object... args) {
|
||||
e((Throwable) null, args);
|
||||
}
|
||||
|
||||
public static void e(Throwable throwable, Object... args) {
|
||||
if (!isEnabled(Log.ERROR)) {
|
||||
return;
|
||||
}
|
||||
write(Log.ERROR, throwable, build(args));
|
||||
}
|
||||
|
||||
// ---------------- 内部实现 ----------------
|
||||
|
||||
private static boolean isEnabled(int priority) {
|
||||
// debug 包全开;release 包需要用 setprop 显式打开,避免把日志带上线
|
||||
return BuildConfig.DEBUG || Log.isLoggable(TAG, priority);
|
||||
}
|
||||
|
||||
private static String build(Object[] args) {
|
||||
StringBuilder builder = new StringBuilder(96);
|
||||
builder.append(caller());
|
||||
|
||||
if (args != null && args.length > 0) {
|
||||
builder.append(" | ");
|
||||
for (int index = 0; index < args.length; index++) {
|
||||
if (index > 0) {
|
||||
builder.append(' ');
|
||||
}
|
||||
builder.append(stringify(args[index]));
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 取调用方位置(类名.方法名:行号)。
|
||||
*
|
||||
* <p>做法是「跳过 L 自己的所有连续栈帧,取紧随其后的那一帧」,而不是
|
||||
* 「跳过 class == L 的帧」—— 后者在 Android 上会出错:
|
||||
* {@code Thread.getStackTrace()} 的栈顶是 {@code dalvik.system.VMStack.getThreadStackTrace}
|
||||
* (行号 -2,native 方法),它既不是 L 也不是 Thread,会被当成调用方返回,
|
||||
* 于是每条日志的前缀都变成 {@code VMStack.getThreadStackTrace:-2}。
|
||||
*
|
||||
* <p>顺带也处理了 L 内部互相调用的情况({@code e(args)} → {@code e(null, args)}),
|
||||
* 因为连续帧会被一起跳过,取到的仍是真正的外部调用方。
|
||||
*/
|
||||
private static String caller() {
|
||||
StackTraceElement[] frames = Thread.currentThread().getStackTrace();
|
||||
String self = L.class.getName();
|
||||
|
||||
int index = 0;
|
||||
while (index < frames.length && !self.equals(frames[index].getClassName())) {
|
||||
index++;
|
||||
}
|
||||
while (index < frames.length && self.equals(frames[index].getClassName())) {
|
||||
index++;
|
||||
}
|
||||
if (index >= frames.length) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
StackTraceElement frame = frames[index];
|
||||
String className = frame.getClassName();
|
||||
String simpleName = className.substring(className.lastIndexOf('.') + 1);
|
||||
return simpleName + "." + frame.getMethodName() + ":" + frame.getLineNumber();
|
||||
}
|
||||
|
||||
private static String stringify(Object value) {
|
||||
if (value == null) {
|
||||
return "null";
|
||||
}
|
||||
if (value instanceof Throwable) {
|
||||
return Log.getStackTraceString((Throwable) value);
|
||||
}
|
||||
if (value instanceof Object[]) {
|
||||
return Arrays.deepToString((Object[]) value);
|
||||
}
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
private static void write(int priority, Throwable throwable, String message) {
|
||||
String body = (message == null || message.isEmpty()) ? "-" : message;
|
||||
|
||||
if (body.length() <= MAX_CHUNK) {
|
||||
Log.println(priority, TAG, body);
|
||||
}
|
||||
else {
|
||||
int total = (body.length() + MAX_CHUNK - 1) / MAX_CHUNK;
|
||||
for (int index = 0; index < total; index++) {
|
||||
int start = index * MAX_CHUNK;
|
||||
int end = Math.min(body.length(), start + MAX_CHUNK);
|
||||
Log.println(priority, TAG, "[" + (index + 1) + "/" + total + "] " + body.substring(start, end));
|
||||
}
|
||||
}
|
||||
|
||||
if (throwable != null) {
|
||||
Log.println(priority, TAG, Log.getStackTraceString(throwable));
|
||||
}
|
||||
}
|
||||
}
|
||||
69
AndroidStation/app/src/main/res/drawable/app_banner.xml
Normal file
69
AndroidStation/app/src/main/res/drawable/app_banner.xml
Normal file
@ -0,0 +1,69 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Android TV 桌面横幅(320×180)。
|
||||
声明了 LEANBACK_LAUNCHER 就必须提供 banner,否则 lint 直接报 MissingTvBanner 错误。
|
||||
|
||||
这里用矢量而不是 PNG:工程内保持零二进制资源,任何分辨率都不会糊。
|
||||
中间的扫描框字形与启动图标的风格保持一致。
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="320dp"
|
||||
android:height="180dp"
|
||||
android:viewportWidth="320"
|
||||
android:viewportHeight="180">
|
||||
|
||||
<!-- 底色 -->
|
||||
<path
|
||||
android:fillColor="#1565C0"
|
||||
android:pathData="M0,0h320v180h-320z" />
|
||||
|
||||
<!-- 左侧装饰:三道渐隐的横线 -->
|
||||
<path
|
||||
android:fillColor="#33FFFFFF"
|
||||
android:pathData="M28,72h56v6h-56z" />
|
||||
<path
|
||||
android:fillColor="#26FFFFFF"
|
||||
android:pathData="M28,90h40v6h-40z" />
|
||||
<path
|
||||
android:fillColor="#1AFFFFFF"
|
||||
android:pathData="M28,108h24v6h-24z" />
|
||||
|
||||
<!-- 中间扫描框:四角 -->
|
||||
<path
|
||||
android:pathData="M110,82 L110,62 L130,62"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="8" />
|
||||
<path
|
||||
android:pathData="M190,62 L210,62 L210,82"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="8" />
|
||||
<path
|
||||
android:pathData="M210,98 L210,118 L190,118"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="8" />
|
||||
<path
|
||||
android:pathData="M130,118 L110,118 L110,98"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="8" />
|
||||
|
||||
<!-- 扫描线 -->
|
||||
<path
|
||||
android:fillColor="#FFB300"
|
||||
android:pathData="M122,87h76v6h-76z" />
|
||||
|
||||
<!-- 右侧装饰:三个设备指示点 -->
|
||||
<path
|
||||
android:fillColor="#FFB300"
|
||||
android:pathData="M246,74m-7,0a7,7 0 1,0 14,0a7,7 0 1,0 -14,0" />
|
||||
<path
|
||||
android:fillColor="#66FFFFFF"
|
||||
android:pathData="M246,90m-7,0a7,7 0 1,0 14,0a7,7 0 1,0 -14,0" />
|
||||
<path
|
||||
android:fillColor="#66FFFFFF"
|
||||
android:pathData="M246,106m-7,0a7,7 0 1,0 14,0a7,7 0 1,0 -14,0" />
|
||||
|
||||
</vector>
|
||||
22
AndroidStation/app/src/main/res/drawable/bg_button.xml
Normal file
22
AndroidStation/app/src/main/res/drawable/bg_button.xml
Normal file
@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
按钮底:遥控器聚焦时高亮,方便在电视上确认当前焦点位置。
|
||||
-->
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<item android:state_focused="true">
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/accent" />
|
||||
<stroke
|
||||
android:width="4dp"
|
||||
android:color="@color/text_primary" />
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/brand" />
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
</selector>
|
||||
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
破坏性操作的按钮底(目前只有「清空记录」)。
|
||||
跟普通的 bg_button(品牌蓝)分开:混在一排蓝按钮里太容易点到。
|
||||
-->
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<item android:state_focused="true">
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/state_error" />
|
||||
<stroke
|
||||
android:width="4dp"
|
||||
android:color="@color/text_primary" />
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/danger" />
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
</selector>
|
||||
13
AndroidStation/app/src/main/res/drawable/bg_card.xml
Normal file
13
AndroidStation/app/src/main/res/drawable/bg_card.xml
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
卡片底:比页面底色(@color/bg)亮一档的面 + 圆角 + 一圈细边。
|
||||
设置页改成 tab + 卡片后用它(样式 CardPanel)。
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="@color/item_bg" />
|
||||
<corners android:radius="10dp" />
|
||||
<stroke
|
||||
android:width="1dp"
|
||||
android:color="@color/divider" />
|
||||
</shape>
|
||||
13
AndroidStation/app/src/main/res/drawable/bg_header.xml
Normal file
13
AndroidStation/app/src/main/res/drawable/bg_header.xml
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
页头背景:从上到下由浅到深的轻微渐变。
|
||||
纯平色的话页头跟内容区糊成一片,加一点梯度就能自然分层,又不会抢内容。
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<gradient
|
||||
android:angle="270"
|
||||
android:endColor="@color/header_bottom"
|
||||
android:startColor="@color/header_top"
|
||||
android:type="linear" />
|
||||
</shape>
|
||||
11
AndroidStation/app/src/main/res/drawable/bg_panel.xml
Normal file
11
AndroidStation/app/src/main/res/drawable/bg_panel.xml
Normal file
@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
设置页输入框的底:给输入区域一个明确的四周边界。
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="@color/bg" />
|
||||
<stroke
|
||||
android:width="1dp"
|
||||
android:color="@color/divider" />
|
||||
</shape>
|
||||
@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 自适应图标前景层:只画「扫描框 + 扫描线」字形,留出安全区 -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
|
||||
<path
|
||||
android:pathData="M34,44 L34,34 L44,34"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M64,34 L74,34 L74,44"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M74,64 L74,74 L64,74"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M44,74 L34,74 L34,64"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
|
||||
<path
|
||||
android:fillColor="#FFB300"
|
||||
android:pathData="M40,52h28v4h-28z" />
|
||||
|
||||
</vector>
|
||||
373
AndroidStation/app/src/main/res/layout/activity_main.xml
Normal file
373
AndroidStation/app/src/main/res/layout/activity_main.xml
Normal file
@ -0,0 +1,373 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
设备端主界面:左边是本机身份与服务状态,右边是扫码结果。
|
||||
页面本身不需要遥控器操作,只有底部两个按钮可聚焦。
|
||||
-->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/bg"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_header"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="32dp"
|
||||
android:paddingTop="14dp"
|
||||
android:paddingEnd="32dp"
|
||||
android:paddingBottom="14dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/app_name"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="26sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_device_name"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="18dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="18sp" />
|
||||
|
||||
<Space
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="1dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_clock"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:fontFamily="monospace"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="22sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="20dp"
|
||||
android:paddingEnd="24dp"
|
||||
android:paddingBottom="16dp">
|
||||
|
||||
<!-- 左:设备信息 -->
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_marginEnd="18dp"
|
||||
android:layout_weight="1.1"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="20dp"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingEnd="20dp"
|
||||
android:paddingBottom="16dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<View
|
||||
android:layout_width="4dp"
|
||||
android:layout_height="22dp"
|
||||
android:layout_marginEnd="10dp"
|
||||
android:background="@color/accent" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/main_info_title"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_name" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_name"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_mac" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_mac"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_ip" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_ip"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_version" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_version"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_service" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_service"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_discovery" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_discovery"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="8dp"
|
||||
android:paddingBottom="8dp">
|
||||
|
||||
<TextView
|
||||
style="@style/InfoLabel"
|
||||
android:text="@string/main_label_total" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_info_total"
|
||||
style="@style/InfoValue" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 右:扫码结果 -->
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="20dp"
|
||||
android:paddingTop="16dp"
|
||||
android:paddingEnd="20dp"
|
||||
android:paddingBottom="16dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<View
|
||||
android:layout_width="4dp"
|
||||
android:layout_height="22dp"
|
||||
android:layout_marginEnd="10dp"
|
||||
android:background="@color/accent" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/main_scan_title"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_last_code"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:ellipsize="end"
|
||||
android:fontFamily="monospace"
|
||||
android:maxLines="2"
|
||||
android:textColor="@color/accent"
|
||||
android:textSize="34sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_last_time"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:layout_marginTop="14dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/main_recent_title"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_recent"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_weight="1"
|
||||
android:fontFamily="monospace"
|
||||
android:gravity="top"
|
||||
android:lineSpacingExtra="5dp"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/main_hint"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_header"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="12dp"
|
||||
android:paddingEnd="24dp"
|
||||
android:paddingBottom="12dp">
|
||||
|
||||
<Button
|
||||
android:id="@+id/btn_settings"
|
||||
style="@style/ActionButton"
|
||||
android:text="@string/main_action_settings" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btn_clear"
|
||||
style="@style/ActionButton"
|
||||
android:layout_marginStart="12dp"
|
||||
android:background="@drawable/bg_button_danger"
|
||||
android:text="@string/main_action_clear" />
|
||||
|
||||
<Space
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="1dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/main_footer"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
216
AndroidStation/app/src/main/res/layout/activity_settings.xml
Normal file
216
AndroidStation/app/src/main/res/layout/activity_settings.xml
Normal file
@ -0,0 +1,216 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 服务设置:设备名 / 服务端口 / 发现端口 / 启停开关 -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/bg"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_header"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="32dp"
|
||||
android:paddingTop="14dp"
|
||||
android:paddingEnd="32dp"
|
||||
android:paddingBottom="14dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/settings_title"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="26sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<Space
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="1dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/settings_header_hint"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<ScrollView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="32dp"
|
||||
android:paddingTop="20dp"
|
||||
android:paddingEnd="32dp"
|
||||
android:paddingBottom="20dp">
|
||||
|
||||
<!-- 设备 -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="16dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/settings_section_device"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
style="@style/SettingsLabel"
|
||||
android:text="@string/settings_name_label" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/et_device_name"
|
||||
style="@style/SettingsInput"
|
||||
android:hint="@string/settings_name_hint"
|
||||
android:inputType="text"
|
||||
android:maxLength="32" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 服务 -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="16dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/settings_section_service"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
style="@style/SettingsLabel"
|
||||
android:text="@string/settings_service_port_label" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/et_service_port"
|
||||
style="@style/SettingsInput"
|
||||
android:inputType="number"
|
||||
android:maxLength="5" />
|
||||
|
||||
<TextView
|
||||
style="@style/SettingsLabel"
|
||||
android:text="@string/settings_discovery_port_label" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/et_discovery_port"
|
||||
style="@style/SettingsInput"
|
||||
android:inputType="number"
|
||||
android:maxLength="5" />
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/sw_service_enabled"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:text="@string/settings_service_enabled"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/sw_discovery_enabled"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/settings_discovery_enabled"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="14dp"
|
||||
android:lineSpacingExtra="4dp"
|
||||
android:text="@string/settings_note"
|
||||
android:textColor="@color/text_secondary"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 当前状态 -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="20dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/settings_section_status"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/tv_settings_status"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="10dp"
|
||||
android:lineSpacingExtra="5dp"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="16sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
|
||||
<View
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="1dp"
|
||||
android:background="@color/divider" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_header"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="24dp"
|
||||
android:paddingTop="12dp"
|
||||
android:paddingEnd="24dp"
|
||||
android:paddingBottom="12dp">
|
||||
|
||||
<Space
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="1dp"
|
||||
android:layout_weight="1" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btn_back"
|
||||
style="@style/ActionButton"
|
||||
android:text="@string/settings_back" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/btn_save"
|
||||
style="@style/ActionButton"
|
||||
android:layout_marginStart="12dp"
|
||||
android:text="@string/settings_save" />
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- API 26+ 自适应图标 -->
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/brand" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- API 21~25 的图标回退:带底色的完整矢量(VectorDrawable 自 API 21 起原生支持) -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
|
||||
<path
|
||||
android:fillColor="#1565C0"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
|
||||
<path
|
||||
android:pathData="M34,44 L34,34 L44,34"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M64,34 L74,34 L74,44"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M74,64 L74,74 L64,74"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
<path
|
||||
android:pathData="M44,74 L34,74 L34,64"
|
||||
android:strokeColor="#FFFFFF"
|
||||
android:strokeLineCap="square"
|
||||
android:strokeWidth="6" />
|
||||
|
||||
<path
|
||||
android:fillColor="#FFB300"
|
||||
android:pathData="M40,52h28v4h-28z" />
|
||||
|
||||
</vector>
|
||||
BIN
AndroidStation/app/src/main/res/raw/voice_0.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_0.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_1.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_1.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_2.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_2.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_3.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_3.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_4.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_4.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_5.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_5.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_6.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_6.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_7.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_7.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_8.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_8.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_9.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_9.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_a.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_a.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_b.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_b.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_c.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_c.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_d.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_d.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_e.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_e.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_f.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_f.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_g.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_g.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_h.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_h.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_i.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_i.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_j.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_j.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_k.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_k.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_l.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_l.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_m.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_m.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_n.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_n.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_o.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_o.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_p.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_p.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_q.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_q.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_r.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_r.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_s.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_s.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_start_pack.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_start_pack.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_t.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_t.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_u.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_u.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_v.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_v.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_w.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_w.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_welcome.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_welcome.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_x.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_x.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_y.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_y.wav
Normal file
Binary file not shown.
BIN
AndroidStation/app/src/main/res/raw/voice_z.wav
Normal file
BIN
AndroidStation/app/src/main/res/raw/voice_z.wav
Normal file
Binary file not shown.
18
AndroidStation/app/src/main/res/values/colors.xml
Normal file
18
AndroidStation/app/src/main/res/values/colors.xml
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="brand">#1565C0</color>
|
||||
<color name="accent">#FFB300</color>
|
||||
<color name="bg">#121212</color>
|
||||
<color name="text_primary">#FFFFFF</color>
|
||||
<color name="text_secondary">#B0BEC5</color>
|
||||
|
||||
<color name="item_bg">#1E1E1E</color>
|
||||
|
||||
<color name="state_error">#EF5350</color>
|
||||
<color name="danger">#8C2F2B</color>
|
||||
|
||||
<color name="divider">#33FFFFFF</color>
|
||||
|
||||
<color name="header_top">#1C2733</color>
|
||||
<color name="header_bottom">#131A21</color>
|
||||
</resources>
|
||||
58
AndroidStation/app/src/main/res/values/strings.xml
Normal file
58
AndroidStation/app/src/main/res/values/strings.xml
Normal file
@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">扫码终端</string>
|
||||
|
||||
<!-- 设备端主界面 -->
|
||||
<string name="main_info_title">设备信息</string>
|
||||
<string name="main_scan_title">扫码结果</string>
|
||||
<string name="main_label_name">设备名称</string>
|
||||
<string name="main_label_mac">MAC 地址</string>
|
||||
<string name="main_label_ip">IP 地址</string>
|
||||
<string name="main_label_version">型号 / 版本</string>
|
||||
<string name="main_label_service">扫码服务</string>
|
||||
<string name="main_label_discovery">设备发现</string>
|
||||
<string name="main_label_total">累计扫码</string>
|
||||
<string name="main_version_value">%1$s · %2$s</string>
|
||||
<string name="main_total_value">%1$d 条</string>
|
||||
<string name="main_service_running">运行中 · TCP %1$d · 已连接 %2$d</string>
|
||||
<string name="main_service_failed">启动失败:%1$s</string>
|
||||
<string name="main_discovery_running">运行中 · UDP %1$d</string>
|
||||
<string name="main_discovery_failed">启动失败:%1$s</string>
|
||||
<string name="main_waiting">等待扫码…</string>
|
||||
<string name="main_last_time">扫码时间:%1$s</string>
|
||||
<string name="main_recent_title">最近扫码</string>
|
||||
<string name="main_recent_empty">暂无扫码记录</string>
|
||||
<string name="main_hint">请使用 USB 扫码枪扫描条码</string>
|
||||
<string name="main_action_settings">服务设置</string>
|
||||
<string name="main_action_clear">清空记录</string>
|
||||
<string name="main_footer">USB 扫码枪 → 扫码服务 → 桌面端</string>
|
||||
<string name="main_cleared">扫码记录已清空</string>
|
||||
|
||||
<!-- 通用状态 -->
|
||||
<string name="status_disabled">未启用</string>
|
||||
<string name="status_starting">启动中</string>
|
||||
<string name="value_unknown">未获取到</string>
|
||||
|
||||
<!-- 服务设置 -->
|
||||
<string name="settings_title">服务设置</string>
|
||||
<string name="settings_header_hint">不改 IP,只配置服务</string>
|
||||
<string name="settings_section_device">设备</string>
|
||||
<string name="settings_name_label">设备名称</string>
|
||||
<string name="settings_name_hint">桌面端发现的设备名</string>
|
||||
<string name="settings_section_service">服务</string>
|
||||
<string name="settings_service_port_label">扫码服务端口(TCP)</string>
|
||||
<string name="settings_discovery_port_label">设备发现端口(UDP)</string>
|
||||
<string name="settings_service_enabled">启用扫码服务</string>
|
||||
<string name="settings_discovery_enabled">允许被桌面端发现</string>
|
||||
<string name="settings_note">桌面端会在局域网内自动发现本机,并连接上面的扫码服务端口读取 USB 扫码枪结果。\n默认:TCP 8087 / UDP 48899。修改后请与桌面端约定保持一致。</string>
|
||||
<string name="settings_section_status">当前状态</string>
|
||||
<string name="settings_status">MAC %1$s · IP %2$s\n扫码服务:%3$s\n设备发现:%4$s</string>
|
||||
<string name="settings_save">保存</string>
|
||||
<string name="settings_back">返回</string>
|
||||
<string name="settings_saved">已保存,服务已重启</string>
|
||||
<string name="settings_saved_with_error">已保存,但服务启动异常:%1$s</string>
|
||||
<string name="settings_error_name">设备名称不能为空</string>
|
||||
<string name="settings_error_service_port">扫码服务端口要写成 1~65535 的数字</string>
|
||||
<string name="settings_error_discovery_port">设备发现端口要写成 1~65535 的数字</string>
|
||||
<string name="settings_error_same_port">两个端口不能相同</string>
|
||||
</resources>
|
||||
72
AndroidStation/app/src/main/res/values/styles.xml
Normal file
72
AndroidStation/app/src/main/res/values/styles.xml
Normal file
@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
|
||||
<!-- 设备端统一用深色底 + 无 ActionBar -->
|
||||
<style name="Theme.AndroidStation" parent="Theme.AppCompat.NoActionBar">
|
||||
<item name="colorPrimary">@color/brand</item>
|
||||
<item name="colorPrimaryDark">@color/bg</item>
|
||||
<item name="colorAccent">@color/accent</item>
|
||||
<item name="android:windowBackground">@color/bg</item>
|
||||
<item name="android:textColorPrimary">@color/text_primary</item>
|
||||
<item name="android:windowFullscreen">true</item>
|
||||
</style>
|
||||
|
||||
<!-- 底部操作按钮:遥控器聚焦时变成琥珀色 -->
|
||||
<style name="ActionButton">
|
||||
<item name="android:layout_width">wrap_content</item>
|
||||
<item name="android:layout_height">48dp</item>
|
||||
<item name="android:minWidth">112dp</item>
|
||||
<item name="android:background">@drawable/bg_button</item>
|
||||
<item name="android:focusable">true</item>
|
||||
<item name="android:paddingStart">20dp</item>
|
||||
<item name="android:paddingEnd">20dp</item>
|
||||
<item name="android:textAllCaps">false</item>
|
||||
<item name="android:textColor">@color/text_primary</item>
|
||||
<item name="android:textSize">16sp</item>
|
||||
</style>
|
||||
|
||||
<!-- 设备信息行:左标签右值 -->
|
||||
<style name="InfoLabel">
|
||||
<item name="android:layout_width">112dp</item>
|
||||
<item name="android:layout_height">wrap_content</item>
|
||||
<item name="android:textColor">@color/text_secondary</item>
|
||||
<item name="android:textSize">16sp</item>
|
||||
</style>
|
||||
|
||||
<style name="InfoValue">
|
||||
<item name="android:layout_width">0dp</item>
|
||||
<item name="android:layout_height">wrap_content</item>
|
||||
<item name="android:layout_weight">1</item>
|
||||
<item name="android:ellipsize">end</item>
|
||||
<item name="android:maxLines">2</item>
|
||||
<item name="android:textColor">@color/text_primary</item>
|
||||
<item name="android:textSize">16sp</item>
|
||||
</style>
|
||||
|
||||
<!-- 设置页表单 -->
|
||||
<style name="SettingsLabel">
|
||||
<item name="android:layout_width">match_parent</item>
|
||||
<item name="android:layout_height">wrap_content</item>
|
||||
<item name="android:layout_marginTop">14dp</item>
|
||||
<item name="android:textColor">@color/text_secondary</item>
|
||||
<item name="android:textSize">15sp</item>
|
||||
</style>
|
||||
|
||||
<style name="SettingsInput">
|
||||
<item name="android:layout_width">match_parent</item>
|
||||
<item name="android:layout_height">wrap_content</item>
|
||||
<item name="android:layout_marginTop">4dp</item>
|
||||
<item name="android:background">@drawable/bg_panel</item>
|
||||
<item name="android:focusable">true</item>
|
||||
<item name="android:focusableInTouchMode">true</item>
|
||||
<item name="android:paddingStart">12dp</item>
|
||||
<item name="android:paddingTop">9dp</item>
|
||||
<item name="android:paddingEnd">12dp</item>
|
||||
<item name="android:paddingBottom">9dp</item>
|
||||
<item name="android:singleLine">true</item>
|
||||
<item name="android:textColor">@color/text_primary</item>
|
||||
<item name="android:textColorHint">@color/text_secondary</item>
|
||||
<item name="android:textSize">16sp</item>
|
||||
</style>
|
||||
|
||||
</resources>
|
||||
26
AndroidStation/build.gradle
Normal file
26
AndroidStation/build.gradle
Normal file
@ -0,0 +1,26 @@
|
||||
// 顶层构建脚本:沿用「buildscript + allprojects」经典写法,仓库统一走国内镜像。
|
||||
buildscript {
|
||||
repositories {
|
||||
maven { url 'https://maven.aliyun.com/repository/google' }
|
||||
maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.7.3'
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
maven { url 'https://maven.aliyun.com/repository/google' }
|
||||
maven { url 'https://maven.aliyun.com/repository/public' }
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register('clean', Delete) {
|
||||
delete rootProject.layout.buildDirectory
|
||||
}
|
||||
380
AndroidStation/docs/udp-48899-protocol.md
Normal file
380
AndroidStation/docs/udp-48899-protocol.md
Normal file
@ -0,0 +1,380 @@
|
||||
# UDP 48899 设备发现协议(ScanHome / 庆科 High-Flying)
|
||||
|
||||
> 来源:设备商工具 `E:\BaiduNetdiskDownload\ScanHome网口配置\IOTService`
|
||||
> 分析方式:实测抓包 + 反查运行配置 + 提取 jar 内字符串常量。
|
||||
> 标注 **[实测]** 的是抓到的原始数据,**[代码]** 来自 jar 常量,**[推断]** 需真机复验。
|
||||
|
||||
## 1. 结论摘要
|
||||
|
||||
局域网设备发现走 **UDP 广播**:工具向 `255.255.255.255:48899` 发一段 **JSON**,
|
||||
设备回包给发送方,工具据此得到设备 MAC / IP / 型号等信息,随后切到设备的管理端口做配置。
|
||||
|
||||
- **报文是纯文本 JSON**,`PasswordEn=0` 时**不加密**(见 §5)。
|
||||
- 广播**间隔约 3 秒**,设备 **30 秒**无响应判掉线。
|
||||
- 广播里的 `ConnectMode` 决定**是否顺带改写设备的服务器地址**——配置端必须用 `Forbidden`。
|
||||
|
||||
## 2. 端口分配
|
||||
|
||||
来自 `IOTService\IOTService\res\ep_tool.properties` **[代码]**:
|
||||
|
||||
| 配置项 | 值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `UDP_BROADCAST_PORT` | **48899** | 广播目标端口(设备在此监听) |
|
||||
| `UDP_LOCAL_PORT` | 48897 | 工具本地端口 |
|
||||
| `JCMDUDP_PORT` | 48896 | JCMD 协议 UDP 端口 |
|
||||
| `JCMDTCP_PORT_START/END` | 48898 / 49898 | JCMD 协议 TCP 端口段 |
|
||||
| `VPATH_UDP_PORT` | 28987 | 虚拟串口 UDP |
|
||||
| `VPATH_TCP_PORT_START/END` | 28990 / 29990 | 虚拟串口 TCP 端口段 |
|
||||
| `VTH_SERVER_PORT` | 28986 | — |
|
||||
| `SCAN_INTERVAL` | 2999 ms | 广播间隔 [代码] |
|
||||
| `DEVICE_TIMEOUT` | 30000 ms | 掉线判定 |
|
||||
| `IOT_HEARTBEAT_INTERVAL` | 30 | 心跳 |
|
||||
| `ZONE` | `EPort` | 区域标识,出现在报文里 |
|
||||
|
||||
另实测到设备的管理端口是 **UDP 5555**(见 §4)。
|
||||
|
||||
## 3. 广播请求报文 **[实测]**
|
||||
|
||||
抓到的原始包(161 字节,UTF-8,无换行):
|
||||
|
||||
```json
|
||||
{"Agent":0,"Type":"EP_Tool","PasswordEn":0,"ServPort":0,"Version":"3.1.3f",
|
||||
"ConnectMode":"Forbidden","Zone":"EPort","ServEn":1,"ServAddr":"0.0.0.0","ClientEn":0}
|
||||
```
|
||||
|
||||
字段含义(对照 `iotservice/device/jcmd/JcmdBroadcast.pack()` **[代码]**):
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `Agent` | int | 代理号,0 = 本机直连 |
|
||||
| `Type` | String | 报文类型,固定 `EP_Tool` |
|
||||
| `Version` | String | 工具版本,实测 `3.1.3f`(取 `iotservice/IOTService.version`) |
|
||||
| `PasswordEn` | int | **是否启用密码/加密**,0 = 明文 |
|
||||
| `Zone` | String | 区域,`EPort` |
|
||||
| `ConnectMode` | String | **是否改写设备服务器配置**,`Forbidden` = 只发现不修改 |
|
||||
| `ServEn` | int | 是否让设备启用「主动连接服务器」 |
|
||||
| `ServAddr` | String | 让设备连接的服务器地址,`0.0.0.0` 表示不改 |
|
||||
| `ServPort` | int | 同上,端口 0 表示不改 |
|
||||
| `ClientEn` | int | 是否启用客户端模式 |
|
||||
| `DevMac` | String | **定向查询**时才有:指定 MAC 只查该设备(广播时省略) |
|
||||
|
||||
注意抓包里**没有 `DevMac`**,因为它只在定向查询时出现——`JcmdBroadcast` 里该字段是按需 `put` 的。
|
||||
|
||||
## 4. 交互时序
|
||||
|
||||
日志 `IOTService\IOTService\log.txt` 第 15–31 行 **[实测]**:
|
||||
|
||||
```
|
||||
15: VcomManager started...
|
||||
16: Start to Scan...
|
||||
17: ***VcomDriver recv len:55 ← 设备心跳
|
||||
19: VCOM recv heartBeat!
|
||||
20: ***VcomDriver recv len:62 ← 设备发现回复(62 字节)
|
||||
22: ..VCOM recv add! ← 识别为新设备
|
||||
23-28: (另外两台设备,同样 62 字节)
|
||||
29: Device ACCF23EA6D8C is on!192.168.10.83:48899
|
||||
30: vcomudp channel connected!
|
||||
31: Send:10-Bytes,To:192.168.10.83/5555 ← 切到设备管理端口
|
||||
```
|
||||
|
||||
所以完整流程是:
|
||||
|
||||
1. PC 广播 JSON → `255.255.255.255:48899`(多网卡时每个广播地址各发一次)
|
||||
2. **设备回一段明文 JSON 给发送方**(实测 **188~189 字节**,见 §6)
|
||||
3. PC 与设备建立 `vcomudp` 通道做后续配置
|
||||
|
||||
> 日志里的 `***VcomDriver recv len:62` / `len:55` 是**另一条链路**(vcom 心跳)的长度,
|
||||
> 不是广播回复;广播回复实测是 188~189 字节,不要混。
|
||||
|
||||
### 两个关键行为 [实测]
|
||||
|
||||
- **回复发往「广播的源地址 + 源端口」**。工具发送用的是临时端口(实测 53278),
|
||||
不是 `UDP_LOCAL_PORT=48897`。
|
||||
→ **在 48899 上 bind 收不到回复**,必须自己发广播并在**同一个 socket** 上收。
|
||||
- **一次广播可能收到多个回复**:实测发 10 次探测收到 20 个包。
|
||||
因为同时发往 `255.255.255.255` 与子网广播 `192.168.11.255`,
|
||||
同一块网卡上的设备**两个包都收得到,于是各回一次**。
|
||||
→ 实现时必须**按 MAC 去重**,不能按“收到几个包”算设备数。
|
||||
- 设备回复的**源端口是 48899**(即设备从自己的 48899 发出)。
|
||||
|
||||
## 5. 加密
|
||||
|
||||
`util/AESCrypt.class` **[代码]**:
|
||||
|
||||
- 硬编码密钥(16 字符 = AES-128):`` `&hFiotseRViCe$' ``
|
||||
- 算法:`AES/CBC/NoPadding`,IV 取密钥自身
|
||||
- `HFEncrypt(byte[])` = `padding()` + `EncryptCBC()`;`HFDecrypt(byte[])` = `DecryptCBC()` + `unPadding()`
|
||||
- 提供 `byteToHexString` / `hexStringToByte` 一组十六进制辅助方法
|
||||
|
||||
**但实测广播报文是明文。** 结合 `PasswordEn=0` 与配置里没有任何密码项,可以判断:
|
||||
**未设密码时收发都不加密**,AES 只在设了密码的场景启用(`HFEncrypt` 内部对空密钥做了短路)。
|
||||
|
||||
> 这意味着接入时**不需要实现 AES**——先按明文做,等遇到设了密码的设备再补。
|
||||
> 若将来要支持加密,注意 `NoPadding` + 自定义 padding 需要逐字节对齐还原。
|
||||
|
||||
## 6. 设备回复报文 **[实测]**
|
||||
|
||||
实测抓到一台真实设备(`192.168.9.208`,与探测机同在 `192.168.11.56/22` 网段),
|
||||
**188~189 字节,明文 JSON**:
|
||||
|
||||
```json
|
||||
{"Agent":0,"Type":"E10C","Version":"1.41.1","ClientEn":1,"HostName":"8号",
|
||||
"CustomerID":"E10C","Uptime":"0-Day 0:8:44\r\n","Zone":"EPort",
|
||||
"UdpSupport":1,"MAC":"402A8FBB15D8","State":"Idle"}
|
||||
```
|
||||
|
||||
| 字段 | 示例值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `Agent` | `0` | 代理号 |
|
||||
| `Type` | `E10C` | **设备型号**(非固定值,这里是 E10C) |
|
||||
| `Version` | `1.41.1` | **设备固件版本** |
|
||||
| `ClientEn` | `1` | 客户端模式开关 |
|
||||
| `HostName` | `8号` | 设备名,**UTF-8 编码**(用 GBK 解会乱码) |
|
||||
| `CustomerID` | `E10C` | 客户/型号标识 |
|
||||
| `Uptime` | `0-Day 0:8:44\r\n` | 运行时长,**字符串尾部带转义的 `\r\n`**,解析时要 trim |
|
||||
| `Zone` | `EPort` | 区域,与请求一致 |
|
||||
| `UdpSupport` | `1` | 是否支持 UDP 配置 |
|
||||
| `MAC` | `402A8FBB15D8` | **设备唯一标识**,12 位十六进制无分隔 |
|
||||
| `State` | `Idle` | 设备状态 |
|
||||
|
||||
### 字段名对照
|
||||
|
||||
`JcmdBroadcast.parse(JSONObject, Device)` 还会读
|
||||
`Status / productID / uartStatus / uartSetup / swVer / Local / position`——
|
||||
但这些**不在广播回复里**,应该是**定向查询**(带 `DevMac`)或连上之后才返回。
|
||||
|
||||
与**云端 bridge** 协议的字段名不同,两套不要混:
|
||||
|
||||
| 含义 | 局域网广播回复 | 云端 bridge |
|
||||
| --- | --- | --- |
|
||||
| MAC | `MAC` | `DevMac` |
|
||||
| 型号 | `Type` / `CustomerID` | `ModuleType` |
|
||||
| 版本 | `Version` | `Version` |
|
||||
| 在线 | `State` | `Online` |
|
||||
| 设备名 | `HostName` | `HostName` |
|
||||
|
||||
> 设备型号实测到 `E10C`;云端日志里出现过的型号:
|
||||
> `E10` / `E20` / `E30` / `EP10` / `EP20` / `HF2211` / `HF5111A` / `HF5111B` / `HF2221` /
|
||||
> `HF5142A` / `HF5142B` / `HF5182` / `HF5111` / `HF2111` / `HF2411` / `HF2421` / `HF2321` / `HF9111` / `HF5122`。
|
||||
|
||||
## 7. 接入建议
|
||||
|
||||
### 7.1 发现方(桌面端)
|
||||
|
||||
1. 广播地址用 `255.255.255.255`,端口 48899;本机有**多块网卡时每块各广播一次**(实测抓到 2 个包,间隔 64ms)。
|
||||
2. 发送消息体直接照抄上面那段 JSON,**务必保留 `ConnectMode":"Forbidden"`**,
|
||||
否则可能被误当成「配置指令」改写设备的服务器地址。
|
||||
3. 用**同一个 socket** 发广播并收回复(绑临时端口);发完等 ~1 秒再收,
|
||||
**不要**用 48899 去 bind 收回复。
|
||||
4. **按 `MAC` 去重**:同一台设备会因为收到多个广播地址而回多个包(实测 2 个/次)。
|
||||
5. 设备名按 **UTF-8** 解码(`HostName` 实测含中文「8号」)。
|
||||
6. 扫描周期参考 3 秒,设备 30 秒无回复即标记离线。
|
||||
7. 若收不到回复,优先排查 AP/交换机是否开了**客户端隔离**(AP isolation)。
|
||||
|
||||
### 7.2 设备端(本工程 AndroidStation)
|
||||
|
||||
AndroidStation 扮演的是「网口扫码设备」这一侧:
|
||||
|
||||
- **UDP 48899**:`DiscoveryResponder` 绑定 48899,收到 `{"Type":"EP_Tool",...}` 就按 §6 的字段
|
||||
回复自己的 `MAC / HostName / Type / Version / Uptime / State`。回复走同一个 socket,
|
||||
源端口就是 48899。
|
||||
- **TCP 8087**:`ScanServer` 监听服务端口(默认 8087,与桌面端 `ScanProtocol.TcpPort` 一致),
|
||||
桌面端主动连上来;USB 扫码结果按 **CRLF 结尾的 UTF-8 行**推送。桌面端连上后下发的
|
||||
扫码枪串口设置指令会被读取并丢弃(本机是 USB HID,不做串口透传)。
|
||||
- **JCMD**:兼容桌面端「添加通道」用到的 `10001 / 10003 / 10005 / 10017`:
|
||||
- `10003 + PL:["SOCK"]` → 返回一条 `packcenter / TCP-SERVER / 8087`;
|
||||
- `10003 + PL:["SYS"]` → 返回 `HostName / IpAddr / DhcpEn=1` 等只读信息;
|
||||
- `10005` 写 `SYS.HostName` 会更新设备名;写 `SOCK.LocalPort` 会改本地服务端口并重启监听;
|
||||
- `10017` 直接确认(设置已经落到 SharedPreferences);
|
||||
- `20003` 只确认,不重启本机。
|
||||
- **不改 IP**:本机不提供网络参数写入,`SYS` 里的地址只读上报。
|
||||
- 只需 `INTERNET` 权限(UDP/TCP 都是普通 socket,不需要系统应用权限)。
|
||||
|
||||
## 8. 待复验
|
||||
|
||||
- [x] ~~设备回复的确切内容~~ → 已实测:明文 JSON,188~189 字节,见 §6
|
||||
- [ ] **定向查询(带 `DevMac`)的回复**是否包含 `productID` / `swVer` / `Local` / `position` 等字段
|
||||
- [ ] 设备管理端口 5555 的 10 字节命令格式
|
||||
- [ ] 设了密码的设备是否真的走 AES,密钥是否就是那个硬编码值
|
||||
- [ ] 是否存在**只回包不响应广播**的设备(即必须先定向查询)
|
||||
|
||||
## 9. 控制命令(JCMD)**[实测]**
|
||||
|
||||
发现之后的配置/控制走同一套机制。证据来自官方工具 V2 的运行日志
|
||||
(`IOTService\IOTService_V2\logs\log.log`):
|
||||
|
||||
```
|
||||
SendJcmd(289C6E833560):{"JCMD":1,"PL":["SYS","UART","SOCK"],"CID":10001},to:169.254.1.1/48899
|
||||
Recv:{"CID":10002,"RC":0,"Remain":1,"PL":{"SOCK":[...]}}
|
||||
SendJcmd(289C6E833560):{"JCMD":1,"Remain":1,"CID":10002},to:169.254.1.1/48899 ← 没取完就继续要
|
||||
Recv:{"CID":10002,"RC":0,"Remain":0,"PL":{"SYS":{...}}}
|
||||
```
|
||||
|
||||
### 传输
|
||||
|
||||
- **UDP 单播**到设备自己的 IP,端口 **48899**(与发现同一个端口)。
|
||||
实测 604 次 `SendJcmd` **全部**发往 48899。
|
||||
- **不需要握手**,发现完直接发。
|
||||
- 靠**目标 IP** 区分设备,请求里**不带** `MAC`。
|
||||
|
||||
### 报文结构
|
||||
|
||||
请求:
|
||||
|
||||
```json
|
||||
{"JCMD": 1, "CID": <命令号>, "PL": <可选载荷>, "Remain": <可选,取后续分片时带>}
|
||||
```
|
||||
|
||||
响应:
|
||||
|
||||
```json
|
||||
{"CID": <响应号>, "RC": <错误码>, "Remain": <0|1>, "PL": <可选载荷>}
|
||||
```
|
||||
|
||||
- `RC = 0` 表示成功(`JCMD_ERR_SUCCUSS`)。
|
||||
- `Remain = 1` 表示设备还有后续分片,客户端要用 **响应 CID** 再发一次带 `Remain:1` 的请求,
|
||||
直到 `Remain = 0`。这就是状态查询要来回多次的原因。
|
||||
|
||||
### CID 命令表(`iotservice.device.jcmd.Jcmd`,javap 读出)
|
||||
|
||||
| CID | 名称 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 10001 / 10002 | `JCMD_GET_STATE` | 取状态(`PL:["SYS","UART","SOCK"]`) |
|
||||
| 10003 / 10004 | `JCMD_GET_CONFIG` | 取配置 |
|
||||
| 10005 / 10006 | `JCMD_SET_CONFIG` | 写配置 |
|
||||
| 10007–10010 | `*_CONFIG_XML` | 读/写 XML 配置 |
|
||||
| 10011 / 10012 | `JCMD_WIFISCAN` | WiFi 扫描 |
|
||||
| 10013–10018 | `*_SCRIPT` / `*_FSETTING` | 脚本与出厂设置 |
|
||||
| 10019–10022 | `*_FLASH_PARA` | Flash 参数 |
|
||||
| 10023 / 10024 | `JCMD_GET_NLOG` | 取运行日志 |
|
||||
| 20001 / 20002 | `JCMD_DO_RELOAD` | 重载配置 |
|
||||
| **20003 / 20004** | **`JCMD_DO_RESTART`** | **重启设备** |
|
||||
| 20005 / 20006 | `JCMD_DO_UPGRADE` | 固件升级 |
|
||||
| 20009–20012 | `JCMD_MODBUS_*` | Modbus 读写 |
|
||||
| 30001 / 30002 | `JCMD_DO_DATASEND` | 透传发数据 |
|
||||
| 40001 / 40002 | `JCMD_LOG` | 日志 |
|
||||
| 90000 | `JCMD_CONNECTED` | 连接标记 |
|
||||
|
||||
错误码:`RC = 0` 成功;`1` 失败;`2` 需要 PL;`3` 需要 SockName;`4` 还有更多;
|
||||
`5` JCMD 被占用;`6` 已断开;`7` 超时;`8` 无需操作。
|
||||
|
||||
### 系统配置读写(已实现,实机验证通过)
|
||||
|
||||
**读配置:CID 10003 → 10004**
|
||||
|
||||
```
|
||||
-> {"JCMD":1,"PL":["SYS"],"CID":10003}
|
||||
<- {"CID":10004,"RC":0,"Remain":0,"PL":{"SYS":{...}}}
|
||||
```
|
||||
|
||||
- `PL` 是**段名数组**。只要 SYS 就传 `["SYS"]`(实测可用,返回也更小);
|
||||
官方工具传的是 `["SYS","UART","SOCK"]`。
|
||||
- `Remain=1` 时用**响应 CID** 续取:`{"JCMD":1,"Remain":1,"CID":10004}`。
|
||||
实测 E10C 读 SYS 一次返回,不分片。
|
||||
|
||||
**SYS 字段**(实测 E10C 全字段):
|
||||
|
||||
| 字段 | 示例 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `User` / `Password` | `admin` / `admin` | Web/Telnet 登录账号,**明文返回** |
|
||||
| `HostName` | `8号` | 设备名(UTF-8) |
|
||||
| `DhcpEn` | `0` | 0 = 静态,1 = DHCP |
|
||||
| `IpAddr` | `192.168.9.208` | IP 地址 |
|
||||
| `Mask` | `255.255.252.0` | 掩码——**字段名是 `Mask`,不是 `NetMask`** |
|
||||
| `GateWay` | `192.168.8.1` | 网关(注意 G/W 大写) |
|
||||
| `Dns` | `192.168.8.1` | DNS |
|
||||
| 其余 | | `Telnet*` / `Web*` / `Ipv6*` / `ntp*` / `ModbusTime` / `Longitude` / `Latitude` / `Lang` |
|
||||
|
||||
> ⚠️ **字段集因型号而异**:官方日志里另一台设备还有 `NetworkMode` / `WiFi*` /
|
||||
> `LanIpAddress` / `LanMarsk` / `EthernetMode` / `SmartConfig`,而这台 E10C 没有。
|
||||
|
||||
**切到 DHCP 的实测行为(2026-10-15)**
|
||||
|
||||
`{"JCMD":1,"PL":{"SYS":{"DhcpEn":1}},"CID":10005}` + 保存:
|
||||
|
||||
- **不需要重启**就生效(实测 `Uptime` 未归零)。
|
||||
- 设备**保持原 IP 可达**(本例仍是 `192.168.9.208`;不排除是 DHCP 恰好分配了同一地址)。
|
||||
- ⚠️ **`IpAddr` / `Mask` / `GateWay` 会被清零成 `0.0.0.0`**,`Dns` 保留。
|
||||
所以**改回静态时这三个字段必须一起写**,只写 `DhcpEn=0` 会让设备拿 `0.0.0.0` 跑:
|
||||
|
||||
```
|
||||
-> {"JCMD":1,"PL":{"SYS":{"DhcpEn":0,"IpAddr":"192.168.9.208",
|
||||
"Mask":"255.255.252.0","GateWay":"192.168.8.1","Dns":"192.168.8.1"}},"CID":10005}
|
||||
```
|
||||
|
||||
- **兜底手段**:换 IP 后设备仍在 48899 上广播,所以「广播发现」是把设备找回来的可靠方式。
|
||||
实测 `tools/device-restart.ps1`(不带参数)就能找回并列出当前 IP。
|
||||
|
||||
**写配置:CID 10005 → 10006,增量**
|
||||
|
||||
```
|
||||
-> {"JCMD":1,"PL":{"SYS":{"Dns":"192.168.8.1"}},"CID":10005}
|
||||
<- {"CID":10006,"RC":0}
|
||||
```
|
||||
|
||||
只传要改的字段。**不要回传整份配置**:字段集因型号而异,整份回写会把设备上
|
||||
本应用不认识的字段一并覆盖掉。
|
||||
|
||||
**DO_RELOAD:CID 20001 → 20002 —— ⚠️ 不是「应用配置」,不要用**
|
||||
|
||||
```
|
||||
-> {"JCMD":1,"PL":["SYS","UART","SOCK"],"CID":20001}
|
||||
<- {"CID":20002,"RC":0}
|
||||
```
|
||||
|
||||
官方工具里 `Reload` 是设备状态窗口上一个**独立按钮**(`ui/DlgStatus.btnReload`,
|
||||
确认文案 "Do you want to do Reload?"),与 `Restart`、`F-Set Clear` / `Default Setting`
|
||||
(对应 `JCMD_SET_FSETTING` 10017)是三个不同动作,所以它**不是**恢复出厂。
|
||||
|
||||
但它也**不是「让配置生效」**——实测它会把改动抹掉。同一台设备上写 `HostName` 的对照实验:
|
||||
|
||||
| 操作 | 读回结果 |
|
||||
| --- | --- |
|
||||
| 写入 + `DO_RELOAD` | `Eport-E10C`(出厂默认)❌ 改动丢了 |
|
||||
| 只写入、**不 reload** | `8号工作台` ✅ |
|
||||
| 只写入 + **重启设备** | `8号工作台` ✅(重启后 `Uptime` 归零,确认真的重启过) |
|
||||
|
||||
- 佐证:官方工具里有一条文案 `Config OK! And Restart Device.`
|
||||
——改完配置,官方期望的是**重启**,不是 reload。
|
||||
- 所以本项目的做法是:**`SET_CONFIG` 写完就结束,什么都不补。**
|
||||
`SET_CONFIG` 会落盘并对重启免疫,不需要额外动作。
|
||||
|
||||
> 两个附带观察(机制均未确认):
|
||||
> `DO_RELOAD` 之后 `ModbusTime` 从 `0` 变成 `-1`;
|
||||
> 本项目发的 `Restart`(CID 20003)在设备上**延后几分钟**才真正复位
|
||||
> (探测期间 `Uptime` 从 `3:12` 掉到 `0:40`)。
|
||||
|
||||
AndroidStation 侧:只处理 `SYS.HostName` 与 `SOCK.LocalPort`,其余网络字段只读上报。
|
||||
PC 侧:`tools/device-config.ps1`(读直接执行;写要 `-Yes`;**不要加 `-Reload`**)。
|
||||
|
||||
### 重启设备(已实现,实机验证通过)
|
||||
|
||||
```
|
||||
发 {"JCMD":1,"CID":20003} ← 无 PL
|
||||
收 {"CID":20004,"RC":0}
|
||||
```
|
||||
|
||||
实测日志片段:
|
||||
|
||||
```
|
||||
13:17:25 SendJcmd(289C6E833560):{"JCMD":1,"CID":20003},to:169.254.1.1/48899
|
||||
13:17:25 Restart Device 289C6E833560
|
||||
13:17:25 Recv:{"CID":20004,"RC":0}
|
||||
13:17:25 BroadCast:1 ← 重启后工具暂停广播
|
||||
13:17:30 BroadCast:0 ← 5 秒后恢复
|
||||
```
|
||||
|
||||
> 设备应答后才会真正重启,重启期间会失联一段时间,发现列表里会自然变为离线。
|
||||
|
||||
AndroidStation 侧:收到 `20003` 只回 `RC=0`,不会重启本机(设备端要保持服务在线)。
|
||||
PC 侧:`tools/device-restart.ps1`(默认演练,加 `-Yes` 才真发)。
|
||||
|
||||
## 附:复现命令
|
||||
|
||||
```powershell
|
||||
# 被动监听:只能看到工具/自己发出的广播请求
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Minutes 3
|
||||
|
||||
# 主动探测:自己发广播并在同一 socket 收回复(发现设备用这个)
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Probe -Minutes 2
|
||||
```
|
||||
9
AndroidStation/gradle.properties
Normal file
9
AndroidStation/gradle.properties
Normal file
@ -0,0 +1,9 @@
|
||||
# JVM 参数:UTF-8 必须显式指定,否则中文资源可能乱码
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
|
||||
# 使用 AndroidX(appcompat)
|
||||
android.useAndroidX=true
|
||||
|
||||
# 并行与构建缓存
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
BIN
AndroidStation/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
AndroidStation/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
6
AndroidStation/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
6
AndroidStation/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
#Mon Dec 28 18:07:31 CST 2020
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.11.1-bin.zip
|
||||
172
AndroidStation/gradlew
vendored
Normal file
172
AndroidStation/gradlew
vendored
Normal file
@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
84
AndroidStation/gradlew.bat
vendored
Normal file
84
AndroidStation/gradlew.bat
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
3
AndroidStation/settings.gradle
Normal file
3
AndroidStation/settings.gradle
Normal file
@ -0,0 +1,3 @@
|
||||
rootProject.name = "AndroidStation"
|
||||
|
||||
include ':app'
|
||||
475
AndroidStation/tools/android.ps1
Normal file
475
AndroidStation/tools/android.ps1
Normal file
@ -0,0 +1,475 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
AndroidStation 设备端真机调试脚手架:构建 / 装机 / 启动 / 抓日志。
|
||||
|
||||
.DESCRIPTION
|
||||
约定:薄入口 + 厚实现。所有逻辑都在本脚本里,.vscode/tasks.json 与命令行只做转发。
|
||||
|
||||
已内置处理(都是本机 / 本设备实际踩过的坑):
|
||||
- JAVA_HOME 自动探测(本机 java 不在 PATH)
|
||||
- adb 自动探测(不在 PATH)
|
||||
- 多设备自动记住上次选择(.dev-adb.local.json,不入库)
|
||||
- adb install 失败自动降级为 push + pm install(老盒子报 fork failed)
|
||||
- 启动依次尝试 am start / am start(LEANBACK) / monkey,全失败时明确提示手动启动
|
||||
- logcat 只跟随本应用 tag,并附带 AndroidRuntime:E 以便看到崩溃
|
||||
- 设备端只建 UDP/TCP socket,普通装 /data 即可,不需要系统应用权限
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 dev
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 install -Serial 4235737
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build', 'install', 'run', 'dev', 'logs', 'clean', 'devices', 'help')]
|
||||
[string]$Task = 'help',
|
||||
|
||||
[ValidateSet('debug', 'release')]
|
||||
[string]$Variant = 'debug',
|
||||
|
||||
[string]$Serial = '',
|
||||
|
||||
[switch]$CleanFirst,
|
||||
[switch]$NoLaunch,
|
||||
[switch]$NoLogcat
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# ============================ 常量 ============================
|
||||
|
||||
$ProjectRoot = Split-Path -Parent $PSScriptRoot
|
||||
$PackageName = 'com.gztbyc.scancenter'
|
||||
$ActivityName = "$PackageName/.MainActivity"
|
||||
$LogTag = 'AndroidStation'
|
||||
$StateFile = Join-Path $ProjectRoot '.dev-adb.local.json'
|
||||
$LocalProps = Join-Path $ProjectRoot 'local.properties'
|
||||
|
||||
# ============================ 输出 ============================
|
||||
|
||||
function Write-Step([string]$Message) { Write-Host "[android] $Message" -ForegroundColor Cyan }
|
||||
function Write-Ok([string]$Message) { Write-Host "[android] OK $Message" -ForegroundColor Green }
|
||||
function Write-Warn([string]$Message) { Write-Host "[android] !! $Message" -ForegroundColor Yellow }
|
||||
|
||||
# ============================ 外部命令封装 ============================
|
||||
|
||||
# 统一调用外部程序:不因 stderr 输出而抛异常,并返回退出码与合并后的文本
|
||||
function Invoke-Native {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$FilePath,
|
||||
[string[]]$Arguments = @(),
|
||||
[switch]$Quiet
|
||||
)
|
||||
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
if ($Quiet) {
|
||||
$output = & $FilePath @Arguments 2>&1
|
||||
$text = ($output | Out-String)
|
||||
return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $text }
|
||||
}
|
||||
|
||||
& $FilePath @Arguments
|
||||
return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = '' }
|
||||
}
|
||||
finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
}
|
||||
|
||||
# ============================ 环境探测 ============================
|
||||
|
||||
function Resolve-JavaHome {
|
||||
if ($env:JAVA_HOME) {
|
||||
if (Test-Path (Join-Path $env:JAVA_HOME 'bin\java.exe')) { return $env:JAVA_HOME }
|
||||
}
|
||||
|
||||
$roots = @()
|
||||
if ($env:LOCALAPPDATA) { $roots += (Join-Path $env:LOCALAPPDATA 'Programs\EclipseAdoptium') }
|
||||
$roots += 'C:\Program Files\Eclipse Adoptium'
|
||||
$roots += 'C:\Program Files\Java'
|
||||
|
||||
foreach ($root in $roots) {
|
||||
if (-not (Test-Path $root)) { continue }
|
||||
$jdk = Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
|
||||
Where-Object { Test-Path (Join-Path $_.FullName 'bin\java.exe') } |
|
||||
Sort-Object Name -Descending |
|
||||
Select-Object -First 1
|
||||
if ($jdk) { return $jdk.FullName }
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function Resolve-SdkDir {
|
||||
if (Test-Path $LocalProps) {
|
||||
$match = Select-String -Path $LocalProps -Pattern '^\s*sdk\.dir\s*=' -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($match) {
|
||||
# local.properties 里的 Windows 路径是转义写法(C\:\\Users\\...),需要还原
|
||||
return ($match.Line -split '=', 2)[1].Trim().Replace('\:', ':').Replace('\\', '\')
|
||||
}
|
||||
}
|
||||
if ($env:ANDROID_HOME) { return $env:ANDROID_HOME }
|
||||
if ($env:ANDROID_SDK_ROOT) { return $env:ANDROID_SDK_ROOT }
|
||||
if ($env:LOCALAPPDATA) { return (Join-Path $env:LOCALAPPDATA 'Android\Sdk') }
|
||||
return ''
|
||||
}
|
||||
|
||||
function Resolve-Adb {
|
||||
$candidates = @()
|
||||
$sdk = Resolve-SdkDir
|
||||
if ($sdk) { $candidates += (Join-Path $sdk 'platform-tools\adb.exe') }
|
||||
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Android\Sdk\platform-tools\adb.exe') }
|
||||
|
||||
foreach ($candidate in $candidates) {
|
||||
if (Test-Path $candidate) { return $candidate }
|
||||
}
|
||||
# 退回 PATH
|
||||
$onPath = Get-Command adb.exe -ErrorAction SilentlyContinue
|
||||
if ($onPath) { return $onPath.Source }
|
||||
throw '未找到 adb.exe,请确认 Android SDK platform-tools 已安装'
|
||||
}
|
||||
|
||||
$Adb = $null
|
||||
function Get-Adb {
|
||||
if (-not $script:Adb) { $script:Adb = Resolve-Adb }
|
||||
return $script:Adb
|
||||
}
|
||||
|
||||
# ============================ 设备选择(含记忆) ============================
|
||||
|
||||
function Get-ConnectedDevices {
|
||||
$adb = Get-Adb
|
||||
$result = Invoke-Native $adb @('devices', '-l') -Quiet
|
||||
$devices = @()
|
||||
$abnormal = @()
|
||||
|
||||
foreach ($line in ($result.Output -split "`r?`n")) {
|
||||
if ($line -match '^(\S+)\s+(device|unauthorized|offline|no permissions)\b\s*(.*)$') {
|
||||
if ($Matches[2] -eq 'device') {
|
||||
$devices += [pscustomobject]@{ Serial = $Matches[1]; Desc = $Matches[3].Trim() }
|
||||
}
|
||||
else {
|
||||
$abnormal += "$($Matches[1]) [$($Matches[2])]"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($abnormal.Count -gt 0) {
|
||||
Write-Warn ("下列设备状态异常:" + ($abnormal -join ','))
|
||||
}
|
||||
return $devices
|
||||
}
|
||||
|
||||
function Read-SavedSerial {
|
||||
if (-not (Test-Path $StateFile)) { return '' }
|
||||
try { return (Get-Content $StateFile -Raw | ConvertFrom-Json).serial } catch { return '' }
|
||||
}
|
||||
|
||||
function Save-Serial([string]$Value) {
|
||||
$json = "{`r`n `"serial`": `"$Value`"`r`n}`r`n"
|
||||
try {
|
||||
# 不写 BOM,避免其它工具解析 JSON 出错
|
||||
[System.IO.File]::WriteAllText($StateFile, $json, (New-Object System.Text.UTF8Encoding($false)))
|
||||
}
|
||||
catch {
|
||||
# 写入失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
function Select-Device {
|
||||
if ($Serial) {
|
||||
Save-Serial $Serial
|
||||
return $Serial
|
||||
}
|
||||
|
||||
$devices = @(Get-ConnectedDevices)
|
||||
if ($devices.Count -eq 0) {
|
||||
throw '未检测到已连接设备。请检查 USB / 无线调试,或执行 adb devices 确认。'
|
||||
}
|
||||
|
||||
$saved = Read-SavedSerial
|
||||
if ($saved) {
|
||||
foreach ($device in $devices) {
|
||||
if ($device.Serial -eq $saved) {
|
||||
Write-Step "使用上次选择的设备:$($device.Serial) $($device.Desc)(可用 -Serial 更换)"
|
||||
return $device.Serial
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($devices.Count -eq 1) {
|
||||
Save-Serial $devices[0].Serial
|
||||
Write-Step "使用设备:$($devices[0].Serial) $($devices[0].Desc)"
|
||||
return $devices[0].Serial
|
||||
}
|
||||
|
||||
Write-Host '[android] 检测到多台设备:' -ForegroundColor Cyan
|
||||
for ($i = 0; $i -lt $devices.Count; $i++) {
|
||||
Write-Host (" [{0}] {1} {2}" -f ($i + 1), $devices[$i].Serial, $devices[$i].Desc)
|
||||
}
|
||||
|
||||
if (-not $Host.Name -or [Console]::IsInputRedirected) {
|
||||
throw "多台设备时请用 -Serial 指定,例如:-Serial $($devices[0].Serial)"
|
||||
}
|
||||
|
||||
$answer = Read-Host "请选择设备序号 [1-$($devices.Count)],直接回车取 1"
|
||||
$index = 0
|
||||
if ($answer) { $index = [int]$answer - 1 }
|
||||
if ($index -lt 0 -or $index -ge $devices.Count) { throw "无效序号:$answer" }
|
||||
|
||||
Save-Serial $devices[$index].Serial
|
||||
return $devices[$index].Serial
|
||||
}
|
||||
|
||||
# ============================ 构建 ============================
|
||||
|
||||
function Invoke-Gradle {
|
||||
param([string[]]$Arguments)
|
||||
|
||||
$javaHome = Resolve-JavaHome
|
||||
if ($javaHome) {
|
||||
$env:JAVA_HOME = $javaHome
|
||||
Write-Step "JAVA_HOME = $javaHome"
|
||||
}
|
||||
else {
|
||||
Write-Warn '未探测到 JDK,若构建失败请手动设置 JAVA_HOME'
|
||||
}
|
||||
|
||||
$gradlew = Join-Path $ProjectRoot 'gradlew.bat'
|
||||
if (-not (Test-Path $gradlew)) { throw "未找到 gradlew.bat:$gradlew" }
|
||||
|
||||
Write-Step ("gradlew " + ($Arguments -join ' '))
|
||||
$result = Invoke-Native $gradlew $Arguments
|
||||
if ($result.ExitCode -ne 0) { throw "构建失败(gradlew 退出码 $($result.ExitCode))" }
|
||||
}
|
||||
|
||||
function Get-ApkPath {
|
||||
$dir = Join-Path $ProjectRoot "app\build\outputs\apk\$Variant"
|
||||
$expected = Join-Path $dir "app-$Variant.apk"
|
||||
if (Test-Path $expected) { return $expected }
|
||||
|
||||
if (Test-Path $dir) {
|
||||
$latest = Get-ChildItem -Path $dir -Filter '*.apk' -ErrorAction SilentlyContinue |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||
if ($latest) { return $latest.FullName }
|
||||
}
|
||||
throw "未找到 APK:$expected"
|
||||
}
|
||||
|
||||
function Invoke-Build {
|
||||
if ($CleanFirst) { Invoke-Gradle @('clean', '--console=plain') }
|
||||
|
||||
$variantCap = $Variant.Substring(0, 1).ToUpper() + $Variant.Substring(1)
|
||||
Invoke-Gradle @(":app:assemble$variantCap", '--console=plain')
|
||||
|
||||
$apk = Get-ApkPath
|
||||
$size = [math]::Round((Get-Item $apk).Length / 1MB, 2)
|
||||
Write-Ok "APK = $apk ($size MB)"
|
||||
return $apk
|
||||
}
|
||||
|
||||
# ============================ 装机 ============================
|
||||
|
||||
function Install-Apk {
|
||||
param([string]$TargetSerial, [string]$Apk)
|
||||
|
||||
$adb = Get-Adb
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
Write-Step "adb install -r(第 $attempt/3 次)"
|
||||
$result = Invoke-Native $adb @('-s', $TargetSerial, 'install', '-r', $Apk) -Quiet
|
||||
Write-Host $result.Output.TrimEnd()
|
||||
if ($result.ExitCode -eq 0) {
|
||||
Write-Ok '安装成功'
|
||||
return
|
||||
}
|
||||
if ($attempt -lt 3) { Start-Sleep -Seconds 2 }
|
||||
}
|
||||
|
||||
# 老盒子(Android 7.1.2 等)的流式安装常报 fork failed,改用两段式
|
||||
Write-Warn 'adb install 连续失败,降级为 push + pm install'
|
||||
$remote = '/data/local/tmp/' + [System.IO.Path]::GetFileName($Apk)
|
||||
$push = Invoke-Native $adb @('-s', $TargetSerial, 'push', $Apk, $remote) -Quiet
|
||||
Write-Host $push.Output.TrimEnd()
|
||||
if ($push.ExitCode -ne 0) { throw '推送到设备失败' }
|
||||
|
||||
$install = Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'pm', 'install', '-r', $remote) -Quiet
|
||||
Write-Host $install.Output.TrimEnd()
|
||||
Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'rm', '-f', $remote) -Quiet | Out-Null
|
||||
|
||||
if ($install.Output -notmatch 'Success') { throw 'pm install 失败,请查看上方设备输出' }
|
||||
Write-Ok '安装成功(push + pm install)'
|
||||
}
|
||||
|
||||
# ============================ 预置成系统应用 ============================
|
||||
|
||||
# ============================ 启动 ============================
|
||||
|
||||
function Start-App {
|
||||
param([string]$TargetSerial)
|
||||
|
||||
$adb = Get-Adb
|
||||
Invoke-Native $adb @('-s', $TargetSerial, 'shell', 'am', 'force-stop', $PackageName) -Quiet | Out-Null
|
||||
|
||||
$attempts = @(
|
||||
[pscustomobject]@{
|
||||
Name = 'am start -n'
|
||||
Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-n', $ActivityName)
|
||||
Expect = 'Starting:'
|
||||
},
|
||||
[pscustomobject]@{
|
||||
Name = 'am start (LEANBACK)'
|
||||
Args = @('-s', $TargetSerial, 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN',
|
||||
'-c', 'android.intent.category.LEANBACK_LAUNCHER', '-n', $ActivityName)
|
||||
Expect = 'Starting:'
|
||||
},
|
||||
[pscustomobject]@{
|
||||
Name = 'monkey'
|
||||
Args = @('-s', $TargetSerial, 'shell', 'monkey', '-p', $PackageName,
|
||||
'-c', 'android.intent.category.LAUNCHER', '1')
|
||||
Expect = 'Events injected'
|
||||
}
|
||||
)
|
||||
|
||||
foreach ($attempt in $attempts) {
|
||||
$result = Invoke-Native $adb $attempt.Args -Quiet
|
||||
if ($result.ExitCode -eq 0 -and $result.Output -match [regex]::Escape($attempt.Expect)) {
|
||||
Write-Ok "已启动应用($($attempt.Name))"
|
||||
return $true
|
||||
}
|
||||
|
||||
$firstLine = ($result.Output -split "`r?`n" | Where-Object { $_.Trim() } | Select-Object -First 1)
|
||||
Write-Warn "$($attempt.Name) 未成功:$firstLine"
|
||||
}
|
||||
|
||||
Write-Warn '自动启动失败。部分海思/定制固件的 am 与 monkey 都会报 AMS 空指针,'
|
||||
Write-Warn '本机无法绕过,请用遥控器手动打开「扫描中心」。'
|
||||
return $false
|
||||
}
|
||||
|
||||
# ============================ 日志 ============================
|
||||
|
||||
function Start-Logcat {
|
||||
param([string]$TargetSerial)
|
||||
|
||||
$adb = Get-Adb
|
||||
Invoke-Native $adb @('-s', $TargetSerial, 'logcat', '-c') -Quiet | Out-Null
|
||||
|
||||
Write-Step "跟随日志中(tag=$LogTag,含崩溃栈),Ctrl+C 退出"
|
||||
Write-Host ("[android] 单独抓取:`"$adb`" -s $TargetSerial logcat -v time $LogTag`:V AndroidRuntime:E `*:S") -ForegroundColor DarkGray
|
||||
|
||||
$previous = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& $adb -s $TargetSerial logcat -v time "$($LogTag):V" 'AndroidRuntime:E' '*:S'
|
||||
}
|
||||
finally {
|
||||
$ErrorActionPreference = $previous
|
||||
}
|
||||
}
|
||||
|
||||
# ============================ 帮助 ============================
|
||||
|
||||
function Show-Help {
|
||||
Write-Host @'
|
||||
AndroidStation 设备端真机调试脚手架
|
||||
|
||||
用法:
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\android.ps1 <任务> [选项]
|
||||
|
||||
任务:
|
||||
build 仅构建 APK
|
||||
install 构建 + 安装
|
||||
run 构建 + 安装 + 启动
|
||||
dev 构建 + 安装 + 启动 + 跟随日志(日常开发用这个)
|
||||
logs 只跟随日志(不构建)
|
||||
clean 清理构建产物
|
||||
devices 列出已连接设备与当前记住的设备
|
||||
help 显示本帮助
|
||||
|
||||
选项:
|
||||
-Variant debug|release 构建类型,默认 debug
|
||||
-Serial <序列号> 指定设备(默认自动选择,多设备时记住上次选择)
|
||||
-CleanFirst 构建前先执行 gradle clean(全量重编)
|
||||
-NoLaunch 不自动启动应用
|
||||
-NoLogcat 不跟随日志
|
||||
|
||||
示例:
|
||||
... -File tools\android.ps1 dev
|
||||
... -File tools\android.ps1 install -Serial 4235737
|
||||
... -File tools\android.ps1 dev -CleanFirst
|
||||
... -File tools\android.ps1 run -Variant release
|
||||
'@
|
||||
}
|
||||
|
||||
function Show-Devices {
|
||||
$devices = @(Get-ConnectedDevices)
|
||||
$saved = Read-SavedSerial
|
||||
|
||||
if ($devices.Count -eq 0) {
|
||||
Write-Warn '未检测到已连接设备'
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host '[android] 已连接设备:' -ForegroundColor Cyan
|
||||
foreach ($device in $devices) {
|
||||
$mark = ''
|
||||
if ($saved -and $device.Serial -eq $saved) { $mark = ' <- 当前记住' }
|
||||
Write-Host (" {0} {1}{2}" -f $device.Serial, $device.Desc, $mark)
|
||||
}
|
||||
}
|
||||
|
||||
# ============================ 主流程 ============================
|
||||
|
||||
Set-Location $ProjectRoot
|
||||
|
||||
try {
|
||||
switch ($Task) {
|
||||
'help' { Show-Help }
|
||||
|
||||
'devices' { Show-Devices }
|
||||
|
||||
'clean' {
|
||||
Invoke-Gradle @('clean', '--console=plain')
|
||||
Write-Ok '已清理'
|
||||
}
|
||||
|
||||
'build' {
|
||||
$apk = Invoke-Build
|
||||
# 单独输出一遍路径到管道,便于其它脚本捕获
|
||||
Write-Output $apk
|
||||
}
|
||||
|
||||
'install' {
|
||||
$apk = Invoke-Build
|
||||
Install-Apk -TargetSerial (Select-Device) -Apk $apk
|
||||
}
|
||||
|
||||
'run' {
|
||||
$apk = Invoke-Build
|
||||
$target = Select-Device
|
||||
Install-Apk -TargetSerial $target -Apk $apk
|
||||
if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
|
||||
if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
|
||||
}
|
||||
|
||||
'dev' {
|
||||
$apk = Invoke-Build
|
||||
$target = Select-Device
|
||||
Install-Apk -TargetSerial $target -Apk $apk
|
||||
if (-not $NoLaunch) { Start-App -TargetSerial $target | Out-Null }
|
||||
if (-not $NoLogcat) { Start-Logcat -TargetSerial $target }
|
||||
else { Write-Ok '完成(-NoLogcat 未跟随日志)' }
|
||||
}
|
||||
|
||||
'logs' {
|
||||
Start-Logcat -TargetSerial (Select-Device)
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Host "[android] 失败:$($_.Exception.Message)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
150
AndroidStation/tools/fetch-voice-seeds.ps1
Normal file
150
AndroidStation/tools/fetch-voice-seeds.ps1
Normal file
@ -0,0 +1,150 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
从语音服务一次性抓取播报种子,转换成 Android res/raw 可直接使用的 WAV。
|
||||
|
||||
.DESCRIPTION
|
||||
设备上没有中文 TTS 引擎(只有 PicoTts,无中文数据),所以播报必须在本地做。
|
||||
这个脚本把「0-9、A-Z、开始打包」逐条请求语音服务,下载 WAV 并统一转成
|
||||
44.1kHz / 立体声 / 16-bit PCM(与设备 AudioFlinger 输出一致),
|
||||
去掉首尾静音并提到 1.25x 语速,放到 app/src/main/res/raw/voice_*.wav。
|
||||
运行时只读本地资源,断网也能播报。
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\fetch-voice-seeds.ps1 -Force
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$BaseUrl = 'http://tbdata.gztbyc.com',
|
||||
|
||||
[string]$OutDir = '',
|
||||
|
||||
[string]$Ffmpeg = 'D:\packService\desktop\native\ffmpeg\ffmpeg.exe',
|
||||
|
||||
# 只重新抓某几个 key(例如 -Only welcome);不传则抓全部
|
||||
[string[]]$Only = @(),
|
||||
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if (-not $OutDir) {
|
||||
$scriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
|
||||
$OutDir = Join-Path $scriptDir '..\app\src\main\res\raw'
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Ffmpeg)) {
|
||||
throw "找不到 ffmpeg:$Ffmpeg(可用 -Ffmpeg 指定)"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
|
||||
|
||||
# key = 资源文件名后缀(必须是小写字母/数字/下划线),value = 送给语音服务的文本
|
||||
$tokens = [ordered]@{
|
||||
'0' = '零'
|
||||
'1' = '一'
|
||||
'2' = '二'
|
||||
'3' = '三'
|
||||
'4' = '四'
|
||||
'5' = '五'
|
||||
'6' = '六'
|
||||
'7' = '七'
|
||||
'8' = '八'
|
||||
'9' = '九'
|
||||
'a' = 'A'
|
||||
'b' = 'B'
|
||||
'c' = 'C'
|
||||
'd' = 'D'
|
||||
'e' = 'E'
|
||||
'f' = 'F'
|
||||
'g' = 'G'
|
||||
'h' = 'H'
|
||||
'i' = 'I'
|
||||
'j' = 'J'
|
||||
'k' = 'K'
|
||||
'l' = 'L'
|
||||
'm' = 'M'
|
||||
'n' = 'N'
|
||||
'o' = 'O'
|
||||
'p' = 'P'
|
||||
'q' = 'Q'
|
||||
'r' = 'R'
|
||||
's' = 'S'
|
||||
't' = 'T'
|
||||
'u' = 'U'
|
||||
'v' = 'V'
|
||||
'w' = 'W'
|
||||
'x' = 'X'
|
||||
'y' = 'Y'
|
||||
'z' = 'Z'
|
||||
'start_pack' = '开始打包'
|
||||
'welcome' = '欢迎使用溯源系统,初始化已经完成,扫码即可开始打包'
|
||||
}
|
||||
|
||||
function Get-VoiceSeed {
|
||||
param([string]$Text)
|
||||
|
||||
$encoded = [Uri]::EscapeDataString($Text)
|
||||
$uri = "$BaseUrl/voice/$encoded"
|
||||
$lastError = $null
|
||||
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try {
|
||||
$json = Invoke-RestMethod -Uri $uri -TimeoutSec 30
|
||||
if (-not $json.audio) {
|
||||
throw '接口没有返回 audio 路径'
|
||||
}
|
||||
$audioUri = $BaseUrl + $json.audio
|
||||
$bytes = (Invoke-WebRequest -UseBasicParsing -Uri $audioUri -TimeoutSec 60).Content
|
||||
if (-not $bytes -or $bytes.Length -lt 1024) {
|
||||
throw "音频太小($($bytes.Length) 字节)"
|
||||
}
|
||||
return $bytes
|
||||
}
|
||||
catch {
|
||||
$lastError = $_.Exception.Message
|
||||
Start-Sleep -Seconds (1 * $attempt)
|
||||
}
|
||||
}
|
||||
throw "抓取「$Text」失败:$lastError"
|
||||
}
|
||||
|
||||
$total = $tokens.Count
|
||||
$index = 0
|
||||
foreach ($key in $tokens.Keys) {
|
||||
$index++
|
||||
if ($Only.Count -gt 0 -and $Only -notcontains $key) {
|
||||
continue
|
||||
}
|
||||
$text = $tokens[$key]
|
||||
$target = Join-Path $OutDir "voice_$key.wav"
|
||||
if ((Test-Path $target) -and -not $Force) {
|
||||
Write-Host ("[{0}/{1}] 跳过 {2}(已存在)" -f $index, $total, $target) -ForegroundColor DarkGray
|
||||
continue
|
||||
}
|
||||
|
||||
Write-Host ("[{0}/{1}] {2} -> voice_{3}.wav" -f $index, $total, $text, $key) -ForegroundColor Cyan
|
||||
$bytes = Get-VoiceSeed -Text $text
|
||||
|
||||
$temp = Join-Path $env:TEMP "voice-seed-$key-raw.wav"
|
||||
[IO.File]::WriteAllBytes($temp, $bytes)
|
||||
|
||||
# 去掉首尾静音并把语速提到 1.25x(保持音调),播报更跟手
|
||||
$filter = 'silenceremove=start_periods=1:start_duration=0.02:start_threshold=-45dB:stop_periods=-1:stop_duration=0.02:stop_threshold=-45dB,atempo=1.25'
|
||||
# 设备音频输出固定 44100Hz 立体声;种子也统一成这个格式,老 rk3288 的 AudioTrack 才认
|
||||
& $Ffmpeg -y -loglevel error -i $temp -af $filter -ac 2 -ar 44100 -acodec pcm_s16le $target
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path $target)) {
|
||||
throw "ffmpeg 转换失败:$text"
|
||||
}
|
||||
|
||||
$size = (Get-Item $target).Length
|
||||
Write-Host (" {0} 字节" -f $size) -ForegroundColor DarkGray
|
||||
Remove-Item -Force $temp -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host '语音种子已就绪:' -ForegroundColor Green
|
||||
Get-ChildItem $OutDir -Filter 'voice_*.wav' | Sort-Object Name |
|
||||
Select-Object Name, Length | Format-Table -AutoSize
|
||||
301
AndroidStation/tools/udp-listen.ps1
Normal file
301
AndroidStation/tools/udp-listen.ps1
Normal file
@ -0,0 +1,301 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
监听指定 UDP 端口,打印收到的每一个报文,用于分析局域网设备的广播协议。
|
||||
|
||||
.DESCRIPTION
|
||||
用在「设备发现」的前期调研:把设备发出的广播原样抓下来,看它的
|
||||
载荷格式、广播地址与频率,再去写解析代码。
|
||||
|
||||
每个报文会输出:
|
||||
- 时间、来源 IP:端口、字节数
|
||||
- 十六进制(前 256 字节)
|
||||
- ASCII 可打印视图(不可打印字符显示为 .)
|
||||
- UTF-8 与 GB18030 两种解码结果(中文设备常见两种编码)
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Minutes 5
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Probe -Minutes 2
|
||||
|
||||
.EXAMPLE
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\udp-listen.ps1 -Port 48899 -Minutes 3 -OutFile D:\packets.log
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[int]$Port = 48899,
|
||||
|
||||
[double]$Minutes = 5,
|
||||
|
||||
[string]$OutFile = '',
|
||||
|
||||
# 主动探测:自己发广播,并在同一个 socket 上收回复。
|
||||
# 被动监听收不到设备回复——回包发往「广播的源端口」,不是 48899。
|
||||
[switch]$Probe,
|
||||
|
||||
# 主动探测的重复间隔(毫秒),默认与官方工具 SCAN_INTERVAL=2999 一致
|
||||
[int]$Interval = 3000,
|
||||
|
||||
# 探测载荷,默认用抓包得到的官方报文
|
||||
[string]$Payload = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if (-not $OutFile) {
|
||||
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
|
||||
$OutFile = Join-Path $env:TEMP "udp-$Port-$stamp.log"
|
||||
}
|
||||
|
||||
$lines = New-Object System.Collections.Generic.List[string]
|
||||
|
||||
function Emit([string]$Text) {
|
||||
Write-Host $Text
|
||||
[void]$lines.Add($Text)
|
||||
}
|
||||
|
||||
function Hex-Dump([byte[]]$Bytes, [int]$MaxBytes) {
|
||||
$take = [Math]::Min($Bytes.Length, $MaxBytes)
|
||||
$parts = @()
|
||||
for ($i = 0; $i -lt $take; $i++) {
|
||||
$parts += $Bytes[$i].ToString('X2')
|
||||
}
|
||||
$text = ($parts -join ' ')
|
||||
if ($Bytes.Length -gt $MaxBytes) {
|
||||
$text += " ... (后续 " + ($Bytes.Length - $MaxBytes) + " 字节省略)"
|
||||
}
|
||||
return $text
|
||||
}
|
||||
|
||||
function Ascii-View([byte[]]$Bytes, [int]$MaxBytes) {
|
||||
$take = [Math]::Min($Bytes.Length, $MaxBytes)
|
||||
$chars = @()
|
||||
for ($i = 0; $i -lt $take; $i++) {
|
||||
$b = $Bytes[$i]
|
||||
if ($b -ge 32 -and $b -lt 127) { $chars += [char]$b } else { $chars += '.' }
|
||||
}
|
||||
return (-join $chars)
|
||||
}
|
||||
|
||||
# ---------------- 本机网络情况 ----------------
|
||||
|
||||
Emit ("=" * 72)
|
||||
Emit "UDP 监听端口 : $Port"
|
||||
Emit "监听时长 : $Minutes 分钟"
|
||||
Emit "输出文件 : $OutFile"
|
||||
Emit ("=" * 72)
|
||||
Emit "本机 IPv4 地址(确认与目标设备在同一网段):"
|
||||
$localIps = @()
|
||||
$broadcastAddrs = @()
|
||||
try {
|
||||
$netAddrs = @(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.IPAddress -ne '127.0.0.1' })
|
||||
$localIps = @($netAddrs | ForEach-Object { $_.IPAddress })
|
||||
|
||||
$broadcastAddrs = @($netAddrs | ForEach-Object {
|
||||
$prefix = $_.PrefixLength
|
||||
$bytes = [System.Net.IPAddress]::Parse($_.IPAddress).GetAddressBytes()
|
||||
$mask = 0
|
||||
for ($i = 0; $i -lt $prefix; $i++) { $mask = $mask -bor (1 -shl (31 - $i)) }
|
||||
$maskBytes = [System.BitConverter]::GetBytes([int]$mask)
|
||||
[array]::Reverse($maskBytes)
|
||||
$bcast = @()
|
||||
for ($i = 0; $i -lt 4; $i++) { $bcast += ($bytes[$i] -bor ($maskBytes[$i] -bxor 255)) }
|
||||
($bcast -join '.')
|
||||
})
|
||||
|
||||
for ($i = 0; $i -lt $netAddrs.Count; $i++) {
|
||||
Emit (" {0}/{1} 广播地址 {2}" -f $netAddrs[$i].IPAddress, $netAddrs[$i].PrefixLength, $broadcastAddrs[$i])
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Emit " (无法枚举网卡:$($_.Exception.Message))"
|
||||
}
|
||||
Emit ""
|
||||
|
||||
# ---------------- 探测载荷 ----------------
|
||||
|
||||
# 抓包得到的官方 IOTService 广播报文(明文 JSON)。
|
||||
# ⚠️ ConnectMode 必须保持 Forbidden:它决定设备是否顺带改写自己的服务器地址,
|
||||
# 改成别的值可能把现场设备的配置改掉。
|
||||
$DEFAULT_PAYLOAD = '{"Agent":0,"Type":"EP_Tool","PasswordEn":0,"ServPort":0,"Version":"3.1.3f","ConnectMode":"Forbidden","Zone":"EPort","ServEn":1,"ServAddr":"0.0.0.0","ClientEn":0}'
|
||||
|
||||
if (-not $Payload) { $Payload = $DEFAULT_PAYLOAD }
|
||||
$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($Payload)
|
||||
|
||||
# ---------------- 建立 socket ----------------
|
||||
|
||||
$client = $null
|
||||
$targets = @()
|
||||
|
||||
try {
|
||||
$client = New-Object System.Net.Sockets.UdpClient
|
||||
$client.ExclusiveAddressUse = $false
|
||||
$client.Client.SetSocketOption(
|
||||
[System.Net.Sockets.SocketOptionLevel]::Socket,
|
||||
[System.Net.Sockets.SocketOptionName]::ReuseAddress,
|
||||
$true)
|
||||
|
||||
if ($Probe) {
|
||||
# 绑到临时端口(0 = 由系统分配)。
|
||||
# 设备把回复发回「广播的源端口」,所以必须用同一个 socket 发送与接收——
|
||||
# 绑到 48899 是收不到回复的。
|
||||
$client.Client.Bind((New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)))
|
||||
$client.EnableBroadcast = $true
|
||||
|
||||
# 255.255.255.255 与各网卡的子网广播都发一遍(官方工具也是每块网卡各发一次)
|
||||
$targets = @($targets + '255.255.255.255' + $broadcastAddrs | Select-Object -Unique)
|
||||
Emit "主动探测模式:发往 $($targets -join '、'),端口 $Port,间隔 $Interval ms"
|
||||
}
|
||||
else {
|
||||
$client.Client.Bind((New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, $Port)))
|
||||
Emit "被动监听模式:只收不发(注意:此模式收不到设备回复,只会看到别的工具发出的广播)"
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Host "绑定失败:$($_.Exception.Message)" -ForegroundColor Red
|
||||
Write-Host "可能原因:端口被占用(先关掉占用程序),或需要管理员权限。" -ForegroundColor Yellow
|
||||
if ($client) { $client.Close() }
|
||||
exit 1
|
||||
}
|
||||
|
||||
Emit "已开始(Ctrl+C 可提前结束)"
|
||||
Emit ""
|
||||
|
||||
# 主动探测时用较短的接收超时,保证探测节奏准确
|
||||
if ($Probe) {
|
||||
$client.Client.ReceiveTimeout = [Math]::Max(100, [Math]::Min(500, $Interval))
|
||||
}
|
||||
else {
|
||||
$client.Client.ReceiveTimeout = 1000
|
||||
}
|
||||
|
||||
$deadline = (Get-Date).AddMinutes($Minutes)
|
||||
$nextProbe = (Get-Date)
|
||||
$probeCount = 0
|
||||
$total = 0
|
||||
$sources = @{}
|
||||
$payloads = @{}
|
||||
$utf8 = New-Object System.Text.UTF8Encoding($false)
|
||||
try {
|
||||
$gbk = [System.Text.Encoding]::GetEncoding('GB18030')
|
||||
}
|
||||
catch {
|
||||
$gbk = $null
|
||||
}
|
||||
|
||||
try {
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
|
||||
# 主动探测:到点就再广播一次(设备可能后上电,或上一个包丢了)
|
||||
if ($Probe -and (Get-Date) -ge $nextProbe) {
|
||||
foreach ($target in $targets) {
|
||||
try {
|
||||
[void]$client.Send($payloadBytes, $payloadBytes.Length,
|
||||
(New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($target), $Port)))
|
||||
}
|
||||
catch {
|
||||
Emit (" 广播到 {0} 失败:{1}" -f $target, $_.Exception.Message)
|
||||
}
|
||||
}
|
||||
$probeCount++
|
||||
Emit ("[{0}] 第 {1} 次探测已发出({2} 字节)" -f (Get-Date -Format 'HH:mm:ss.fff'), $probeCount, $payloadBytes.Length)
|
||||
$nextProbe = (Get-Date).AddMilliseconds($Interval)
|
||||
}
|
||||
|
||||
$remote = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)
|
||||
$data = $null
|
||||
|
||||
try {
|
||||
$data = $client.Receive([ref]$remote)
|
||||
}
|
||||
catch [System.Net.Sockets.SocketException] {
|
||||
if ($_.Exception.SocketErrorCode -eq [System.Net.Sockets.SocketError]::TimedOut) {
|
||||
continue
|
||||
}
|
||||
throw
|
||||
}
|
||||
|
||||
$total++
|
||||
$key = "$($remote.Address):$($remote.Port)"
|
||||
if (-not $sources.ContainsKey($key)) { $sources[$key] = 0 }
|
||||
$sources[$key]++
|
||||
|
||||
$ascii = Ascii-View $data 256
|
||||
if (-not $payloads.ContainsKey($ascii)) { $payloads[$ascii] = 0 }
|
||||
$payloads[$ascii]++
|
||||
|
||||
Emit ("[{0}] #{1} 来自 {2} 共 {3} 字节" -f (Get-Date -Format 'HH:mm:ss.fff'), $total, $key, $data.Length)
|
||||
|
||||
# 来源是本机地址时,说明是本机某个进程在广播 —— 顺手把进程揪出来
|
||||
if ($localIps -contains $remote.Address.ToString()) {
|
||||
$owner = $null
|
||||
try {
|
||||
$owner = Get-NetUDPEndpoint -LocalPort $remote.Port -ErrorAction SilentlyContinue
|
||||
}
|
||||
catch {
|
||||
$owner = $null
|
||||
}
|
||||
if ($owner) {
|
||||
$proc = Get-Process -Id $owner.OwningProcess -ErrorAction SilentlyContinue
|
||||
Emit (" ↑ 本机进程:PID {0} {1} {2}" -f $owner.OwningProcess, $proc.ProcessName, $proc.Path)
|
||||
}
|
||||
else {
|
||||
Emit " ↑ 来自本机,但发送方端口已关闭(瞬时 socket,发完即关)"
|
||||
}
|
||||
}
|
||||
|
||||
Emit (" HEX : " + (Hex-Dump $data 256))
|
||||
Emit (" ASCII : " + $ascii)
|
||||
Emit (" UTF-8 : " + $utf8.GetString($data))
|
||||
if ($gbk) {
|
||||
Emit (" GBK : " + $gbk.GetString($data))
|
||||
}
|
||||
Emit ""
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$client.Close()
|
||||
|
||||
Emit ("=" * 72)
|
||||
Emit "监听结束,共发出 $probeCount 次探测,收到 $total 个报文"
|
||||
if ($total -gt 0) {
|
||||
Emit ""
|
||||
Emit "来源统计:"
|
||||
foreach ($k in ($sources.Keys | Sort-Object)) {
|
||||
Emit (" {0} {1} 个" -f $k, $sources[$k])
|
||||
}
|
||||
Emit ""
|
||||
Emit "载荷去重(相同内容只列一次,附出现次数):"
|
||||
foreach ($k in ($payloads.Keys | Sort-Object)) {
|
||||
Emit (" x{0} {1}" -f $payloads[$k], $k)
|
||||
}
|
||||
}
|
||||
else {
|
||||
Emit "没收到任何报文。排查方向:"
|
||||
if ($Probe) {
|
||||
Emit " 1. 设备是否真的在线且在同一网段(跨网段/VLAN 收不到广播)"
|
||||
Emit " 2. Windows 防火墙是否拦了入站 UDP —— 探测包的回复是发回本机临时端口的,"
|
||||
Emit " 没有放行的话会静默丢弃(这是最常见的原因)"
|
||||
Emit " 3. AP/交换机是否开了客户端隔离(AP isolation)"
|
||||
Emit " 4. 设备是否设了密码(PasswordEn=1)—— 那时收发都是 AES 密文,不会回明文"
|
||||
Emit " 5. 端口号是否正确"
|
||||
}
|
||||
else {
|
||||
Emit " 1. 被动模式只能看到别人发出的广播;设备回复是发往广播源端口的,本模式收不到"
|
||||
Emit " → 想抓回复请加 -Probe"
|
||||
Emit " 2. 设备是否真的会主动广播(有些设备只在被询问后才回应)"
|
||||
Emit " 3. Windows 防火墙 / 网段 / VLAN 问题"
|
||||
}
|
||||
}
|
||||
Emit ("=" * 72)
|
||||
|
||||
try {
|
||||
[System.IO.File]::WriteAllLines($OutFile, $lines, (New-Object System.Text.UTF8Encoding($false)))
|
||||
Write-Host ""
|
||||
Write-Host "完整日志已写入:$OutFile"
|
||||
}
|
||||
catch {
|
||||
Write-Host "写日志失败:$($_.Exception.Message)" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
20
README.md
20
README.md
@ -1,6 +1,6 @@
|
||||
# 云仓视频溯源系统
|
||||
|
||||
前后端分离 + 一个浏览器扩展 + 一个 Windows 本机软件(WPF)+ 一个微信小程序,五个目录:
|
||||
前后端分离 + 一个浏览器扩展 + 一个 Windows 本机软件(WPF)+ 一个微信小程序 + 一个 Android 设备端,六个目录:
|
||||
|
||||
```
|
||||
packService/
|
||||
@ -8,7 +8,8 @@ packService/
|
||||
├── frontend/ # Vite + Vue3 + TypeScript(用户端 SPA)
|
||||
├── miniprogram/ # uni-app + Vue3 + TypeScript(微信小程序:抽屉登录(个人中心为整页登录)/ 协议弹窗 / 首页统计 / 扫码记录 / 我的)
|
||||
├── extension/ # Chrome MV3 扩展:注入第三方 WMS 页面,把运单号加工成溯源入口
|
||||
└── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议
|
||||
├── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议
|
||||
└── AndroidStation/ # Android 设备端:UDP 48899 被桌面端发现 + TCP 8087 推送 USB 扫码结果
|
||||
```
|
||||
|
||||
## 端口约定(⚠️ 本机项目多,不要用 Vite 默认的 5173)
|
||||
@ -26,7 +27,12 @@ packService/
|
||||
- 后端端口可用 `PORT=7400 npm run dev` 覆盖(默认 **7300**,配置在 `backend/config/config.default.js` 的 `config.cluster.listen.port`)。
|
||||
- 前端调接口走**同源代理**:Vite 把 `/api`、`/health` 反代到后端(默认 `127.0.0.1:7300`,用 `VITE_BACKEND` 覆盖)。
|
||||
- 联调更方便的做法:直接开后端 `:7300`,由后端(dev)把 `/` 反代到前端 dev server(`FRONTEND_DEV_SERVER`,默认 `http://127.0.0.1:7301`)。
|
||||
- **上线**:后端托管 `frontend/dist`(静态资源 + SPA fallback),`/` 出前端、`/api/*` 出 JSON。
|
||||
- **上线**:前端构建产物发布到 `deployRoot/frontend`,由 **nginx 直接托管**(静态资源 + SPA fallback);`/api/*`、`/health` 由 nginx 反代到 Egg,`/download/*` 由 nginx 直接托管安装包目录。发布走 `cd backend && npm run deploy`(双实例蓝绿发布,详见 [`backend/README.md`](backend/README.md)「发布到服务器」)。
|
||||
- **安装包分发**(`/download/` 由 nginx 直接托管):桌面端 MSI 在 `/download/desktop/`、Android APK 在 `/download/android_client/`,
|
||||
版本信息分别是 `/download/version.json`(桌面端自动更新读这个地址,不能改)和 `/download/android_client/version.json`。
|
||||
单独发版:`cd backend && npm run desktop:publish` / `npm run android:publish`(都只构建+上传,不动后端)。
|
||||
- **生产强制 HTTPS**:站点 vhost 对 HTTP 一律 `301` 到 HTTPS,HSTS 由 `front.conf` 各 location 声明;后端 `config.proxy = true`,`SITE_URL` / `desktopBaseUrl` 均为 `https://`,桌面端安装包内嵌地址也是 HTTPS。
|
||||
- **AndroidStation 设备端**不用这些开发端口:它在局域网上监听 **TCP 8087**(桌面端读扫码结果)和 **UDP 48899**(被桌面端发现),详见 [`AndroidStation/README.md`](AndroidStation/README.md)。
|
||||
|
||||
## 身份与通讯约定
|
||||
|
||||
@ -46,8 +52,8 @@ packService/
|
||||
- [x] 小程序脚手架 `miniprogram/`(uni-app + Vue3 + TS):微信一键登录(code2Session)+ 账号登录双 tab / 首页统计 / 扫码记录 / 个人中心;登录前需阅读并同意协议(版本落库);不强制登录(启动不弹窗,点功能或 401 才提示,符合小程序审核)
|
||||
- [x] 浏览器扩展 `extension/`(MV3,零构建):注入第三方 WMS 页面,在运单号**旁边**渲染「查看打包视频」按钮 → 点按钮打开溯源页
|
||||
- [x] **后端去掉服务端渲染**:删除 `app/controller/page/`、`app/view/`、`app/lib/page.js`、nunjucks / session / CSRF 配置与依赖,后端只剩 JSON 接口
|
||||
- [x] 页面全部迁移到前端:登录 / 注册 / 找回密码 / 扫码 / 扫码确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页
|
||||
- [x] 后端 dev 反代前端(`app/middleware/frontend.js`)+ 生产托管 `frontend/dist`(SPA 深链回退)
|
||||
- [x] 页面全部迁移到前端:登录 / 注册 / 找回密码 / 扫码 / 扫码确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页(仅开发构建,生产不打包)
|
||||
- [x] 后端 dev 反代前端(`app/middleware/frontend.js`);生产由 nginx 直接托管前端构建产物(Egg 只提供 API)
|
||||
- [x] 运维接口加鉴权:`app/controller/admin/` → `internal/`,统一挂 `middleware.internalAuth()`
|
||||
- [x] 新增用户端接口:`/api/web/{stats,devices*,records,test/*}`(范围一律限定在令牌对应的那个用户)
|
||||
- [ ] 扩展:目标地址换成真实打包视频页(现在指向百度占位)—— 在扩展「设置」里改「目标地址模板」即可,需要真实地址
|
||||
@ -76,7 +82,7 @@ packService/
|
||||
cd frontend
|
||||
npm run dev # 7301(VITE_PORT 可覆盖)
|
||||
npm run typecheck # vue-tsc --noEmit
|
||||
npm run build # typecheck + vite build(产物 dist/,后端生产模式托管)
|
||||
npm run build # typecheck + vite build(产物 dist/,发布时由 nginx 直接托管)
|
||||
```
|
||||
|
||||
|
||||
@ -86,7 +92,7 @@ npm run build # typecheck + vite build(产物 dist/,后端生产模式
|
||||
| --- | --- | --- |
|
||||
| `PORT` | `7300` | 后端监听端口 |
|
||||
| `FRONTEND_DEV_SERVER` | `http://127.0.0.1:7301` | 开发时把页面请求反代到哪里 |
|
||||
| `FRONTEND_DIST` | `frontend/dist` | 生产托管的前端构建产物目录 |
|
||||
| `FRONTEND_DIST` | `frontend/dist` | 仅当让 Egg 托管前端时使用(默认由 nginx 托管,`FRONTEND_ENABLE=false`) |
|
||||
| `FRONTEND_ENABLE` | `true` | 关掉后后端不管页面(纯接口模式) |
|
||||
| `INTERNAL_TOKEN` | 空 | 运维接口的静态令牌(header `X-Internal-Token`);不配就只能靠白名单账号的 user JWT |
|
||||
| `INTERNAL_ADMIN_IDS` | `1` | 哪些用户 id 能调运维接口(逗号分隔) |
|
||||
|
||||
@ -34,7 +34,7 @@ packService/backend
|
||||
│ │ │ ├── stats.js # /api/web/stats 首页统计(按当前用户)
|
||||
│ │ │ ├── device.js # /api/web/devices* 我的设备(列表/详情/通道/解绑/删除)
|
||||
│ │ │ ├── record.js # /api/web/records 我的扫码记录(按自己设备过滤)
|
||||
│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口
|
||||
│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口(仅非生产环境注册)
|
||||
│ │ ├── internal/ # 运维/内部(❗需内部令牌,挂在 middleware.internalAuth() 后面)
|
||||
│ │ │ ├── user.js # /api/users* 用户 CRUD(含缓存)
|
||||
│ │ │ ├── wechat.js # /api/wechat/:appid/:openid、bind、tokens、解绑、用户的授权列表
|
||||
@ -159,6 +159,19 @@ npm run db:deploy # ① 建库(有权限时) ② 基线表 sql/schema
|
||||
npm run db:deploy -- --check # 只检查(列出未执行的迁移;有 pending 时退出码 1),适合上线前/CI 卡一道
|
||||
```
|
||||
|
||||
### 生产库迁移(本地执行,目标 = 生产库)
|
||||
|
||||
生产 MySQL 账号是 `packservice@localhost`,只能从服务器本机登录,所以脚本会先建 **SSH 隧道**再跑同一套迁移:
|
||||
|
||||
```bash
|
||||
npm run db:check:prod # 只检查生产库还有哪些迁移没执行(不改库)
|
||||
npm run db:deploy:prod # 基线表 + 全部未执行迁移(幂等,可反复跑)
|
||||
```
|
||||
|
||||
- 连接信息来自本机 `config/env.prod.sh`(`MYSQL_*`),SSH 信息来自 `config/deploy.config.local.cjs`;
|
||||
- 隧道:`127.0.0.1:<随机端口> → <服务器>:127.0.0.1:3306`,执行完自动关闭;
|
||||
- 显式设置的 `MYSQL_*` 环境变量优先于 `config.local.js`(不会被本机开发库密码覆盖)。
|
||||
|
||||
规则(**所有迁移脚本都保留在仓库里,不删不改**):
|
||||
|
||||
| 位置 | 作用 | 什么时候跑 |
|
||||
@ -169,11 +182,166 @@ npm run db:deploy -- --check # 只检查(列出未执行的迁移;有 pendin
|
||||
| `scripts/backfill-snapshot.js`、`scripts/dedupe-scan-records.js` | 一次性数据修复(需带参数,可 `--dry-run`) | 按需手动,不是部署必跑 |
|
||||
|
||||
执行顺序固定为「基线表 → 迁移(按文件名升序)」,所以新库和老库走同一条命令,结果一致;
|
||||
连接信息与运行时同源(环境变量 > `config/config.local.js` > 默认值)。
|
||||
连接信息与运行时同源(环境变量 > `config/config.prod.js`(`EGG_SERVER_ENV=prod`)> `config/config.local.js` > 默认值)。
|
||||
|
||||
> 生产库如果由 DBA 预建、且应用账号没有建库权限,`db:deploy` 会打印一行「跳过建库」后继续,不影响后续迁移。
|
||||
|
||||
|
||||
## 发布到服务器(npm run deploy)
|
||||
|
||||
参考 `D:\wms` 的双实例蓝绿发布:`v1` / `v2` 两个目录轮流发布,新实例健康检查(`/health`)通过后才切 Nginx upstream,再停旧实例;失败会回滚 `current.md` 并保留旧实例继续服务。
|
||||
|
||||
### 一次性准备
|
||||
|
||||
1. 本机:Node 18+、git、tar(Win10/11 自带 bsdtar)、OpenSSH Client(`ssh` / `scp`)。
|
||||
2. 填写发布配置 `config/deploy.config.local.cjs`(该文件已被 `.gitignore` 忽略;若缺失可从模板复制):
|
||||
|
||||
```powershell
|
||||
cd backend
|
||||
# 已存在则直接编辑;缺失时:
|
||||
Copy-Item config/deploy.config.example.cjs config/deploy.config.local.cjs
|
||||
```
|
||||
|
||||
3. 服务器目录结构(首次发布时脚本会自动建 `v1` / `v2` / `.deploy` / `shared-config`):
|
||||
|
||||
```
|
||||
/www/wwwroot/packService/
|
||||
├── current.md # 内容只能是 v1 或 v2
|
||||
├── nginx-upstream.conf # 只有一行:proxy_pass http://127.0.0.1:7301;(API 端口)
|
||||
├── front.conf # nginx 前端静态 + /api、/health 反代 + /download 静态(自动维护)
|
||||
├── frontend/ # 前端构建产物(nginx 直接托管)
|
||||
├── frontend.prev/ # 上一版前端(回退用)
|
||||
├── download/ # 安装包分发(nginx 直接托管)
|
||||
│ ├── version.json # 桌面端版本信息(不缓存,客户端写死这个地址)
|
||||
│ ├── desktop/ # 桌面端 MSI(长缓存)
|
||||
│ └── android_client/ # Android APK + version.json
|
||||
├── shared-config/ # 服务端私有配置(不随发布包走)
|
||||
│ └── env.prod.sh # 启动前 source 的环境变量
|
||||
├── v1/ v2/ # 两个后端发布目录
|
||||
└── .deploy/ # incoming / backups / state
|
||||
```
|
||||
|
||||
站点 vhost 里只需要 include 一次前端/反代配置:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
server_name pack.example.com;
|
||||
|
||||
# 前端静态 + /api、/health 反代 + /download 静态,全部由 front.conf 维护
|
||||
include /www/wwwroot/packService/front.conf;
|
||||
}
|
||||
```
|
||||
|
||||
> `front.conf` 由 `npm run deploy` 自动生成;`nginx-upstream.conf` 里的端口在发布健康检查通过后切换。
|
||||
> 首次发布前先创建 `current.md`(内容 `v1` 或 `v2`);发布总是部署到**另一个**目录。
|
||||
|
||||
> 生产站点强制 HTTPS:vhost 里对 `$scheme != https` 直接 `return 301 https://$host$request_uri`,
|
||||
> 且 `front.conf` 的每个带 `add_header` 的 location 都会重复声明 `Strict-Transport-Security`
|
||||
> (nginx 的 `add_header` 一旦在 location 内出现,就不再继承 server 级配置)。
|
||||
|
||||
4. **服务端私有配置放在 `shared-config/`,不要改版本目录里的 `config.default.js`**
|
||||
(后者是仓库代码,每次发布都会被覆盖)。`shared-config/env.prod.sh` 会在启动前被 `source`,
|
||||
每次发布也会把 `shared-config/config.prod.js`、`config.local.js`(若存在)复制进目标版本目录。
|
||||
|
||||
```bash
|
||||
# /www/wwwroot/packService/shared-config/env.prod.sh(chmod 600)
|
||||
export JWT_SECRET='由 openssl rand -hex 32 生成的随机串'
|
||||
export MYSQL_HOST='127.0.0.1'
|
||||
export MYSQL_PORT='3306'
|
||||
export MYSQL_PASSWORD='...'
|
||||
export REDIS_HOST='127.0.0.1'
|
||||
export REDIS_PASSWORD='...'
|
||||
```
|
||||
|
||||
本项目已经准备好两份生产 env:
|
||||
|
||||
| 文件 | 用途 | 是否提交 |
|
||||
|---|---|---|
|
||||
| `backend/config/env.prod.sh` | 后端运行时变量(`JWT_SECRET`、`MYSQL_*`、`REDIS_*`、`SITE_URL`) | **否**(gitignore,本机权威副本,发布前自动上传到 `shared-config/`) |
|
||||
| `frontend/.env.production` | 前端构建变量(`VITE_*`,不含密钥) | 是 |
|
||||
|
||||
> 改后端 env 后执行 `npm run deploy` 会自动上传并生效;改前端 env 后同样重新发布即可(`deploy` 会重新构建前端)。
|
||||
|
||||
> 生产环境 `config.default.js` 会强制要求 `JWT_SECRET` 环境变量,缺少会启动失败(健康检查不通过,自动保留旧实例)。
|
||||
|
||||
5. 可选:安装提交前检查钩子(禁止提交私有配置 / 运行期产物 / 版本记录):
|
||||
|
||||
```bash
|
||||
npm run setup:hooks
|
||||
```
|
||||
|
||||
### 常用命令
|
||||
|
||||
| 命令 | 说明 |
|
||||
|---|---|
|
||||
| `npm run deploy:precheck` | 检查本地工具、SSH、远端目录 / Node / Nginx / 当前实例健康状态 |
|
||||
| `npm run deploy` | 构建前端 → 打包 → 上传 → 解压安装 → 启动新实例 → 健康检查 → 切 Nginx → 停旧实例 |
|
||||
| `npm run deploy:verify` | 查看当前版本 / 备份并冒烟探测 `/`、`/health`、`/download/version.json` |
|
||||
| `npm run deploy:version` | 查看远端活跃版本与最近一次发布记录(`--history=20` 看历史) |
|
||||
| `npm run deploy:smoke` | 只做冒烟探测 |
|
||||
| `npm run deploy:inspect` | 只看 `.deploy` 状态与备份清单 |
|
||||
| `npm run rollback` | 蓝绿回退到上一个版本目录(不重新解压,秒级切换) |
|
||||
| `npm run rollback -- --backup=backup-<时间戳>.tar.gz` | 用指定备份包恢复当前活跃目录 |
|
||||
| `npm run deploy:cleanup-backups -- backup-xxx.tar.gz` | 删除指定备份包 |
|
||||
|
||||
发布说明:
|
||||
|
||||
- 前端构建产物单独上传到 `deployRoot/frontend`,由 **nginx 直接托管**(SPA 回退到 `index.html`);上一版保留在 `frontend.prev`,`npm run rollback` 会连前端一起切回。
|
||||
nginx 前端/反代配置由发布脚本写入 `deployRoot/front.conf`;Egg 只提供 `/api`、`/health`(`FRONTEND_ENABLE=false`)。
|
||||
`buildFrontend: false` 时跳过前端构建与发布(适合前端完全独立部署)。
|
||||
- 生产发布**不含「测试页」**:前端 `TestView` 只在 dev 构建里注册路由与菜单(生产包不会产出该 chunk),
|
||||
后端 `/api/web/test/*` 只在 `env != prod` 时注册,生产请求直接 404。
|
||||
- 发布包只包含 git 跟踪的源码;版本目录里的 `config/config.prod.js`、`config/config.local.js`、`app/public/download`、`app/public/version` 在清理前暂存、解压后放回,随后再用 `shared-config/` 里的同名配置覆盖,保证所有版本配置一致。
|
||||
- 启动前会 `source shared-config/env.prod.sh`(`JWT_SECRET`、`MYSQL_*`、`REDIS_*` 等);**不要编辑版本目录里的 `config.default.js`**,它属于仓库代码,会被每次发布覆盖。
|
||||
- 每次发布会在 `.deploy/backups/` 留一份旧代码备份(默认保留最近 5 个;`node_modules` / `logs` / `run` / `temp`、安装包目录和服务端私有配置不进备份,它们本身会被保留)。
|
||||
- 需要发布时顺带升级库结构,把 `config/deploy.config.local.cjs` 里的 `remoteDbDeploy` 改成 `true`(远端会先 source `shared-config/env.prod.sh`,再以 `EGG_SERVER_ENV=prod` 执行 `npm run db:deploy`;连接信息来自 `MYSQL_*` 环境变量或 `config.prod.js`)。
|
||||
|
||||
### 桌面端正式包(单独发布,不动后端)
|
||||
|
||||
改桌面端时只需要发安装包,**不用重新发布后端**:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run desktop:build # 只构建(dry-run),产物在 desktop/installer/out
|
||||
npm run desktop:publish # 构建 + 上传 + 刷新 nginx
|
||||
npm run desktop:publish -- --version=1.0.90 --notes="修复 xxx"
|
||||
npm run desktop:publish -- --skip-nginx
|
||||
```
|
||||
|
||||
- 版本默认取本地已有最高版本 + 1(补丁号),也可用 `--version=` 指定;
|
||||
- 构建复用 `desktop/installer/build.ps1 -Environment Production`;
|
||||
- 上传到 `deployRoot/download/desktop/`(MSI),`version.json` 传到 `deployRoot/download/`
|
||||
(路径不能改:老客户端写死 `/download/version.json`;先传 MSI,再原子替换 `version.json`);
|
||||
- nginx 的 `/download/` 静态托管该目录:`version.json` 不缓存,MSI 长缓存;
|
||||
- `desktop/installer/package.config.json` 的 Production `serverBaseUrl` 必须是 `https://`,安装包内嵌的接口 / 下载地址会跟着变;
|
||||
- **谷歌插件一起打进包**:`extension/` 发布到 `<安装目录>\extension`,菜单「工具 → 复制谷歌插件地址」给出该 Windows 路径;
|
||||
- 不会重启 Egg、不会重新发布后端、不会跑数据库迁移;
|
||||
- 前置:.NET 8 SDK、WiX 5.0.2(`dotnet tool install --global wix --version 5.0.2`)、`desktop/native/ffmpeg/ffmpeg.exe`。
|
||||
|
||||
下载地址:`<desktopBaseUrl>/download/desktop/YuncangTraceSetup-<版本>.msi`
|
||||
更新信息:`<desktopBaseUrl>/download/version.json`
|
||||
|
||||
### Android 设备端正式包(单独发布,不动后端)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm run android:build # 只构建(dry-run),产物在 backend/android_client/out
|
||||
npm run android:publish # 构建 + 上传 + 刷新 nginx
|
||||
npm run android:publish -- --version=1.0.2 --notes="扫码上报更稳"
|
||||
npm run android:publish -- --skip-nginx
|
||||
```
|
||||
|
||||
- 构建复用 `backend/android_client/build.ps1 -Environment Production`(配置在 `backend/android_client/package.config.json`,和桌面端同一套路);
|
||||
- 版本默认取已有 APK / version.json 的最高版本 +1 补丁号;`versionCode` 由 `x.y.z` 换算(`major*10000+minor*100+patch`);
|
||||
- 上传到 `deployRoot/download/android_client/`:APK + `version.json`(nginx 对 `version.json` 单独关缓存);
|
||||
- 签名读 `AndroidStation/keystore.properties` + `keystore/*.jks`(**不入库**,发布机必须自行备份);
|
||||
- 前置:JDK 17(`JAVA_HOME`,或自动找 `%LOCALAPPDATA%\Programs\EclipseAdoptium\jdk-*` / Android Studio 的 `jbr`)、
|
||||
Android SDK(`AndroidStation/local.properties` 的 `sdk.dir` 或 `ANDROID_HOME`)。
|
||||
|
||||
下载地址:`<androidBaseUrl>/download/android_client/YuncangScan-<版本>.apk`
|
||||
更新信息:`<androidBaseUrl>/download/android_client/version.json`
|
||||
|
||||
|
||||
## 单元测试
|
||||
|
||||
```bash
|
||||
@ -219,7 +387,7 @@ npm run cov
|
||||
| `SMTP_HOST` | 空 | SMTP 主机;**不配就走开发模式**(验证码只写日志 + 注册页回显,不发真邮件) |
|
||||
| `SMTP_PORT` | `465` | SMTP 端口 |
|
||||
| `SMTP_SECURE` | `true` | 是否用 TLS(465 用 true,587 用 false) |
|
||||
| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号密码(放 `config/config.local.js` 或环境变量) |
|
||||
| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号 / 密码(QQ 邮箱填「授权码」,不是登录密码;放 `shared-config/env.prod.sh` 或环境变量) |
|
||||
| `SMTP_FROM` | `云仓视频溯源系统 <no-reply@...>` | 发件人(默认取 `SITE_NAME` 作显示名) |
|
||||
| `EMAIL_CODE_TTL` | `600` | 邮箱验证码有效期(秒) |
|
||||
| `EMAIL_CODE_RESEND` | `60` | 同一邮箱重发验证码的间隔(秒) |
|
||||
@ -432,15 +600,18 @@ node scripts/backfill-snapshot.js --dry-run
|
||||
| 设备管理 | `/devices` | `/api/web/devices*` |
|
||||
| 扫码记录 | `/records` | `/api/web/records` |
|
||||
| 个人中心 | `/profile` | `/api/web/me*` |
|
||||
| 测试页 | `/test` | `/api/web/test/*`、`/api/wechat/{status,confirm}` |
|
||||
| 测试页(**仅开发构建**,生产不打包) | `/test` | `/api/web/test/*`、`/api/wechat/{status,confirm}` |
|
||||
|
||||
> 「测试页」只在 `vite dev` / 本地开发构建里存在:生产构建不产出 `TestView` 的 chunk,
|
||||
> 路由与左侧菜单也一并去掉;后端 `/api/web/test/*` 只在 `env != prod` 时注册(生产请求返回 404)。
|
||||
|
||||
**后端怎么把页面交出去**(`app/middleware/frontend.js`,只接管「非 `/api`、`/health`」的 GET/HEAD 请求):
|
||||
|
||||
- **开发**(`env=local`):**反代**到 `FRONTEND_DEV_SERVER`(默认 `http://127.0.0.1:7301`,即 `frontend/ && npm run dev`),
|
||||
包含 HMR 的 WebSocket 升级 —— 所以联调只开 `http://127.0.0.1:7300` 一个地址就够(前端热更新照常生效);
|
||||
前端没起来时会回一个 502 提示页,而不是白屏;
|
||||
- **生产**:托管 `FRONTEND_DIST`(默认 `../frontend/dist`);找不到文件且请求要 HTML 时回退 `index.html`
|
||||
(SPA 深链 `/devices` 刷新不会 404);dist 不存在时回 503 并提示先 `npm run build`;
|
||||
- **生产**:本仓库的发布脚手架默认由 **nginx 直接托管** `deployRoot/frontend`,Egg 侧用 `FRONTEND_ENABLE=false` 关闭页面托管(只出 `/api`、`/health`);安装包由 nginx 静态托管 `deployRoot/download`。
|
||||
如果仍想让 Egg 托管(例如没有 nginx),设置 `FRONTEND_ENABLE=true` 并在启动时用 `FRONTEND_DIST` 指向构建产物;找不到文件且请求要 HTML 时回退 `index.html`(SPA 深链不会 404)。
|
||||
- **单测**(`env=unittest`):整个中间件跳过(不连前端、也不要求 dist 存在)。
|
||||
|
||||
## 接口
|
||||
|
||||
250
backend/android_client/build.ps1
Normal file
250
backend/android_client/build.ps1
Normal file
@ -0,0 +1,250 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
打「AndroidStation 设备端」的正式签名 APK,并生成下载用的 version.json。
|
||||
|
||||
.DESCRIPTION
|
||||
1. 按 -Environment 从 package.config.json 取该环境的下载域名 / 目标目录;
|
||||
2. gradlew assembleRelease:版本号用 -PversionName/-PversionCode 覆盖,
|
||||
签名读 AndroidStation\keystore.properties(正式 keystore,不入库);
|
||||
3. 算 MD5 → 写 version.json(version / versionCode / downloadUrl / md5 / size / publishedAt / buildId);
|
||||
4. APK 复制到 out\;copyToServer=true 时再复制到后端:
|
||||
APK → app\public\download\android_client\(nginx 长缓存)
|
||||
version.json → app\public\version\android_client\(由 controller/download.js 关缓存后提供)
|
||||
5. out\ 与后端目录各只保留最近 keepVersions(默认 5)个安装包。
|
||||
|
||||
.PARAMETER Environment
|
||||
Development(连本机 7300)/ Production(正式域名)。
|
||||
|
||||
.PARAMETER Version
|
||||
版本号 x.y.z(必填;发布脚本会按已有包自动 +1 补丁号)。
|
||||
|
||||
.PARAMETER VersionCode
|
||||
Android versionCode(默认由 x.y.z 换算:major*10000 + minor*100 + patch)。
|
||||
|
||||
.PARAMETER ServerBaseUrl
|
||||
覆盖该环境配置里的域名(生成下载地址用,APK 本体不写死域名)。
|
||||
|
||||
.PARAMETER Keep
|
||||
保留多少个历史安装包(默认读 package.config.json 的 keepVersions = 5)。
|
||||
|
||||
.PARAMETER ReleaseNotes
|
||||
写进 version.json 的更新说明。
|
||||
|
||||
.EXAMPLE
|
||||
.\build.ps1 -Environment Production -Version 1.0.1 -ReleaseNotes "扫码上报更稳"
|
||||
|
||||
.NOTES
|
||||
前置:JDK 17、Android SDK(AndroidStation\local.properties 的 sdk.dir 或 ANDROID_HOME)、
|
||||
AndroidStation\keystore.properties + keystore\*.jks(正式签名)。
|
||||
本文件必须保存为 UTF-8 with BOM —— PowerShell 5.1 读无 BOM 脚本会按 GBK 解析,中文注释直接语法报错。
|
||||
#>
|
||||
param(
|
||||
[ValidateSet('Development', 'Production')]
|
||||
[string]$Environment = 'Development',
|
||||
|
||||
[string]$Version,
|
||||
[int]$VersionCode = 0,
|
||||
[string]$ServerBaseUrl,
|
||||
[int]$Keep = 0,
|
||||
[string]$ReleaseNotes = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Read-Utf8([string]$p) {
|
||||
return [System.IO.File]::ReadAllText($p, (New-Object System.Text.UTF8Encoding($false)))
|
||||
}
|
||||
|
||||
function Write-Utf8NoBom([string]$p, [string]$text) {
|
||||
[System.IO.File]::WriteAllText($p, $text, (New-Object System.Text.UTF8Encoding($false)))
|
||||
}
|
||||
|
||||
# ---------------- 1. 配置 ----------------
|
||||
$configPath = Join-Path $PSScriptRoot 'package.config.json'
|
||||
$cfg = Read-Utf8 $configPath | ConvertFrom-Json
|
||||
|
||||
$envProp = $cfg.environments.PSObject.Properties[$Environment]
|
||||
if (-not $envProp) { throw "package.config.json 里没有环境:$Environment" }
|
||||
$envCfg = $envProp.Value
|
||||
|
||||
if (-not $ServerBaseUrl) { $ServerBaseUrl = $envCfg.serverBaseUrl }
|
||||
if (-not $ServerBaseUrl) { throw "环境 $Environment 没配 serverBaseUrl" }
|
||||
$ServerBaseUrl = $ServerBaseUrl.TrimEnd('/')
|
||||
|
||||
if ($Keep -le 0) { $Keep = [int]$cfg.keepVersions }
|
||||
if ($Keep -le 0) { $Keep = 5 }
|
||||
|
||||
$projectDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.projectDir))
|
||||
$outDir = Join-Path $PSScriptRoot 'out'
|
||||
$gradlew = Join-Path $projectDir 'gradlew.bat'
|
||||
if (-not (Test-Path $gradlew)) { throw "找不到 gradlew.bat:$gradlew(检查 package.config.json 的 projectDir)" }
|
||||
|
||||
# ---------------- 2. 版本 ----------------
|
||||
if (-not $Version) { throw "请用 -Version x.y.z 指定版本号(npm run android:publish 会自动带上)" }
|
||||
$Version = $Version.Trim().TrimStart('v', 'V')
|
||||
$null = [version]$Version # 提前校验格式(不合法直接报错)
|
||||
|
||||
$parts = $Version.Split('.')
|
||||
$major = [int]$parts[0]
|
||||
$minor = 0
|
||||
if ($parts.Length -gt 1) { $minor = [int]$parts[1] }
|
||||
$patch = 0
|
||||
if ($parts.Length -gt 2) { $patch = [int]$parts[2] }
|
||||
if ($VersionCode -le 0) { $VersionCode = $major * 10000 + $minor * 100 + $patch }
|
||||
|
||||
Write-Host "环境:$Environment"
|
||||
Write-Host "版本:$Version(versionCode $VersionCode)"
|
||||
Write-Host "工程:$projectDir"
|
||||
|
||||
# ---------------- 3. 环境检查 ----------------
|
||||
$keystoreProps = Join-Path $projectDir 'keystore.properties'
|
||||
if (-not (Test-Path $keystoreProps)) {
|
||||
throw "缺少正式签名配置:$keystoreProps`n(keystore.properties 与 keystore/*.jks 不入库,发布机需自行备份)"
|
||||
}
|
||||
|
||||
$localProps = Join-Path $projectDir 'local.properties'
|
||||
if (-not (Test-Path $localProps) -and -not $env:ANDROID_HOME -and -not $env:ANDROID_SDK_ROOT) {
|
||||
throw "找不到 Android SDK:请写 $localProps 的 sdk.dir 或设置 ANDROID_HOME"
|
||||
}
|
||||
|
||||
$javaHome = $env:JAVA_HOME
|
||||
if (-not $javaHome -or -not (Test-Path (Join-Path $javaHome 'bin\java.exe'))) {
|
||||
$roots = @(
|
||||
'C:\Program Files\Android\Android Studio\jbr',
|
||||
(Join-Path $env:LOCALAPPDATA 'Programs\EclipseAdoptium'),
|
||||
'C:\Program Files\Eclipse Adoptium',
|
||||
'C:\Program Files\Java'
|
||||
)
|
||||
$javaHome = $null
|
||||
foreach ($root in $roots) {
|
||||
if (-not (Test-Path $root)) { continue }
|
||||
if (Test-Path (Join-Path $root 'bin\java.exe')) { $javaHome = $root; break }
|
||||
$child = Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue |
|
||||
Where-Object { Test-Path (Join-Path $_.FullName 'bin\java.exe') } |
|
||||
Sort-Object Name -Descending | Select-Object -First 1
|
||||
if ($child) { $javaHome = $child.FullName; break }
|
||||
}
|
||||
}
|
||||
if (-not $javaHome) { throw '找不到 JDK:请安装 JDK 17 并设置 JAVA_HOME。' }
|
||||
$env:JAVA_HOME = $javaHome
|
||||
Write-Host "JAVA_HOME=$javaHome"
|
||||
|
||||
# ---------------- 4. 构建 APK ----------------
|
||||
Push-Location $projectDir
|
||||
try {
|
||||
& $gradlew --no-daemon assembleRelease "-PversionName=$Version" "-PversionCode=$VersionCode"
|
||||
if ($LASTEXITCODE -ne 0) { throw "gradlew assembleRelease 失败($LASTEXITCODE)" }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$builtApk = Join-Path $projectDir 'app\build\outputs\apk\release\app-release.apk'
|
||||
if (-not (Test-Path $builtApk)) { throw "构建产物不存在:$builtApk" }
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
|
||||
$apkName = [string]$envCfg.apkName
|
||||
if (-not $apkName) { $apkName = 'YuncangScan-{version}.apk' }
|
||||
$apkName = $apkName.Replace('{version}', $Version)
|
||||
$apk = Join-Path $outDir $apkName
|
||||
Copy-Item -Path $builtApk -Destination $apk -Force
|
||||
|
||||
# ---------------- 5. version.json ----------------
|
||||
$hash = (Get-FileHash -Algorithm MD5 -Path $apk).Hash.ToLowerInvariant()
|
||||
$size = (Get-Item $apk).Length
|
||||
$downloadUrl = "$ServerBaseUrl/download/android_client/$apkName"
|
||||
$now = Get-Date
|
||||
|
||||
$versionJson = [ordered]@{
|
||||
version = $Version
|
||||
versionCode = $VersionCode
|
||||
package = 'com.gztbyc.scancenter'
|
||||
downloadUrl = $downloadUrl
|
||||
md5 = $hash
|
||||
size = $size
|
||||
publishedAt = $now.ToString('yyyy-MM-ddTHH:mm:sszzz')
|
||||
buildId = $now.ToString('yyyyMMddHHmmss')
|
||||
environment = $Environment
|
||||
releaseNotes = $ReleaseNotes
|
||||
} | ConvertTo-Json
|
||||
|
||||
$versionFile = Join-Path $outDir 'version.json'
|
||||
Write-Utf8NoBom $versionFile $versionJson
|
||||
|
||||
Write-Host "APK:$apk($([math]::Round($size / 1MB, 1)) MB)"
|
||||
Write-Host "MD5:$hash"
|
||||
Write-Host "下载地址:$downloadUrl"
|
||||
|
||||
# ---------------- 6. 复制到后端 ----------------
|
||||
$skipVersionJson = $false
|
||||
$downloadDir = $null
|
||||
$versionDir = $null
|
||||
|
||||
if ($envCfg.copyToServer -ne $false) {
|
||||
$downloadDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.downloadFolder))
|
||||
$versionDir = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $envCfg.versionFolder))
|
||||
New-Item -ItemType Directory -Force -Path $downloadDir | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path $versionDir | Out-Null
|
||||
|
||||
# 后端已经是更新版本:说明这次在补打旧版本,不能把 version.json 降回去
|
||||
$existingVj = Join-Path $versionDir 'version.json'
|
||||
if (Test-Path $existingVj) {
|
||||
try {
|
||||
$old = (Read-Utf8 $existingVj) | ConvertFrom-Json
|
||||
if ($old.version -and ([version]$old.version -gt [version]$Version)) {
|
||||
$skipVersionJson = $true
|
||||
Write-Warning "后端 version.json 已是更新版本($($old.version)),本次不覆盖它"
|
||||
}
|
||||
}
|
||||
catch { /* 旧文件坏了就当没有 */ }
|
||||
}
|
||||
|
||||
$dstApk = Join-Path $downloadDir $apkName
|
||||
Copy-Item -Path $apk -Destination $dstApk -Force
|
||||
# 刷新 mtime:即使上游还有一层协商缓存,也能认出文件变了
|
||||
(Get-Item $dstApk).LastWriteTime = $now
|
||||
|
||||
if (-not $skipVersionJson) {
|
||||
Write-Utf8NoBom $existingVj $versionJson
|
||||
(Get-Item $existingVj).LastWriteTime = $now
|
||||
}
|
||||
|
||||
Write-Host "已复制到:$downloadDir(APK)、$versionDir(version.json)"
|
||||
}
|
||||
else {
|
||||
Write-Host "(该环境 copyToServer=false,跳过复制到后端)"
|
||||
}
|
||||
|
||||
# ---------------- 7. 只保留最近 N 个安装包 ----------------
|
||||
function Remove-OldPackages([string]$dir, [int]$keep) {
|
||||
if (-not (Test-Path $dir)) { return }
|
||||
|
||||
$items = @(
|
||||
Get-ChildItem -Path $dir -Filter 'YuncangScan-*.apk' -File | ForEach-Object {
|
||||
if ($_.BaseName -match 'YuncangScan-(\d+(\.\d+){1,3})$') {
|
||||
[pscustomobject]@{ File = $_; Ver = [version]$Matches[1] }
|
||||
}
|
||||
} | Sort-Object Ver -Descending
|
||||
)
|
||||
|
||||
$removed = 0
|
||||
$items | Select-Object -Skip $keep | ForEach-Object {
|
||||
Remove-Item $_.File.FullName -Force
|
||||
$removed++
|
||||
Write-Host " 清理旧包:$($_.File.Name)"
|
||||
}
|
||||
|
||||
if ($removed -eq 0) { Write-Host " $dir:共 $($items.Count) 个,未超过 $keep 个" }
|
||||
}
|
||||
|
||||
Write-Host "保留最近 $Keep 个安装包:"
|
||||
Remove-OldPackages $outDir $Keep
|
||||
if ($downloadDir) { Remove-OldPackages $downloadDir $Keep }
|
||||
|
||||
# ---------------- 8. 摘要 ----------------
|
||||
Write-Host ""
|
||||
Write-Host "完成:$apk" -ForegroundColor Green
|
||||
Write-Host "版本文件:$versionFile"
|
||||
Write-Host "下载地址:$downloadUrl"
|
||||
Write-Host "安装:adb install -r `"$apk`"(设备上无需任何特殊权限)"
|
||||
26
backend/android_client/package.config.json
Normal file
26
backend/android_client/package.config.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"$comment": "Android 设备端打包配置(android_client/build.ps1 -Environment Development|Production 读取对应环境,和桌面端 desktop/installer/package.config.json 一个套路)。版本号必须由发布脚本传 -Version 覆盖,versionCode 默认由 x.y.z 换算(major*10000+minor*100+patch)。",
|
||||
"keepVersions": 5,
|
||||
|
||||
"environments": {
|
||||
"Development": {
|
||||
"$comment": "开发环境:后端本机 7300。打包后会把 APK + version.json 复制到后端,本机即可验证下载地址。",
|
||||
"serverBaseUrl": "http://127.0.0.1:7300",
|
||||
"projectDir": "../../AndroidStation",
|
||||
"apkName": "YuncangScan-{version}.apk",
|
||||
"downloadFolder": "../app/public/download/android_client",
|
||||
"versionFolder": "../app/public/version/android_client",
|
||||
"copyToServer": true
|
||||
},
|
||||
|
||||
"Production": {
|
||||
"$comment": "生产环境:正式域名(APK 本身不写域名,只用于生成下载地址)。",
|
||||
"serverBaseUrl": "https://pack.wms.gztbyc.com",
|
||||
"projectDir": "../../AndroidStation",
|
||||
"apkName": "YuncangScan-{version}.apk",
|
||||
"downloadFolder": "../app/public/download/android_client",
|
||||
"versionFolder": "../app/public/version/android_client",
|
||||
"copyToServer": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -12,21 +12,42 @@ const { Controller } = require('egg');
|
||||
* 而 egg-static 生产默认强缓存一年 → 软件永远拿旧的 version.json,永远检测不到更新。
|
||||
*
|
||||
* 所以:
|
||||
* - `version.json` 放在 `app/public/version/`(不在静态 prefix 下),由本控制器读文件;
|
||||
* - 安装包 `*.msi` 仍走 egg-static(`/download/xxx.msi`),文件名带版本号,可以长缓存。
|
||||
* - 版本信息放在 `app/public/version/<平台>/version.json`(不在静态 prefix 下),由本控制器读文件:
|
||||
* desktop → app/public/version/desktop/version.json
|
||||
* (更早的版本放在 app/public/version/version.json,仍作为兜底读一次)
|
||||
* android_client → app/public/version/android_client/version.json
|
||||
* - 安装包本体仍走 egg-static(`/download/desktop/*.msi`、`/download/android_client/*.apk`),
|
||||
* 文件名带版本号,可以长缓存。
|
||||
*
|
||||
* 缓存策略:no-store + no-cache + Expires 0,且不产生 ETag/Last-Modified(不走 304)。
|
||||
* 生产前面若还有 nginx/CDN,也要对 `/download/version.json` 关缓存。
|
||||
* 生产前面若还有 nginx/CDN,也要对这些 version.json 关缓存(见 deploy-lib.cjs 的 buildFrontConf)。
|
||||
*/
|
||||
class DownloadController extends Controller {
|
||||
/** GET /download/version.json */
|
||||
/** GET /download/version.json(桌面端;路径不能改:老客户端写死了这个地址) */
|
||||
async version() {
|
||||
const { ctx, app } = this;
|
||||
const file = path.join(app.baseDir, 'app/public/version/version.json');
|
||||
return this.sendVersion('desktop', [
|
||||
'app/public/version/desktop/version.json',
|
||||
'app/public/version/version.json',
|
||||
]);
|
||||
}
|
||||
|
||||
if (!fs.existsSync(file)) {
|
||||
/** GET /download/android_client/version.json */
|
||||
async androidVersion() {
|
||||
return this.sendVersion('android_client', [
|
||||
'app/public/version/android_client/version.json',
|
||||
]);
|
||||
}
|
||||
|
||||
/** 按候选路径顺序取第一个存在的 version.json,null 缓存直出 */
|
||||
sendVersion(label, candidates) {
|
||||
const { ctx, app } = this;
|
||||
const file = candidates
|
||||
.map(item => path.join(app.baseDir, item))
|
||||
.find(item => fs.existsSync(item));
|
||||
|
||||
if (!file) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: 'version.json 不存在(还没打包过?)' };
|
||||
ctx.body = { ok: false, message: `${label} version.json 不存在(还没打包过?)` };
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@ -82,13 +82,14 @@ class WebAuthController extends Controller {
|
||||
if (!result.ok) ctx.throw(429, result.message);
|
||||
|
||||
ctx.logger.info('[web] 注册验证码已发送到 %s', email);
|
||||
const exposeDevCode = ctx.app.config.env !== 'prod' && Boolean(result.devMode);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
email,
|
||||
// 开发模式(未配 SMTP)把验证码带回来,前端可直接提示;生产不返回
|
||||
devMode: Boolean(result.devMode),
|
||||
code: result.devMode ? result.code : undefined,
|
||||
devMode: exposeDevCode,
|
||||
code: exposeDevCode ? result.code : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -163,13 +164,14 @@ class WebAuthController extends Controller {
|
||||
}
|
||||
|
||||
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
|
||||
const exposeDevUrl = ctx.app.config.env !== 'prod' && Boolean(result.devMode);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
sent: true,
|
||||
// 开发模式(未配 SMTP)把链接返回,前端可直接点开
|
||||
devMode: Boolean(result.devMode),
|
||||
url: result.devMode ? result.url : undefined,
|
||||
devMode: exposeDevUrl,
|
||||
url: exposeDevUrl ? result.url : undefined,
|
||||
},
|
||||
};
|
||||
return;
|
||||
|
||||
@ -26,9 +26,12 @@ module.exports = (app) => {
|
||||
router.get('/health', controller.health.index);
|
||||
|
||||
// ---------- 安装包分发(软件自动更新) ----------
|
||||
// 安装包本体 `GET /download/YuncangTraceSetup-x.y.z.msi` 由 egg-static 提供(config.static);
|
||||
// 安装包本体由 egg-static 提供(config.static):
|
||||
// 桌面端 `GET /download/desktop/YuncangTraceSetup-x.y.z.msi`
|
||||
// Android `GET /download/android_client/YuncangScan-x.y.z.apk`
|
||||
// version.json **必须走路由**:static 命中后不会 next(),改不了缓存头(会被缓存一年)。
|
||||
router.get('/download/version.json', controller.download.version);
|
||||
router.get('/download/android_client/version.json', controller.download.androidVersion);
|
||||
|
||||
// ---------- 协议(公开读取;同意记录在登录时落库) ----------
|
||||
router.get('/api/agreements/current', controller.agreement.current);
|
||||
@ -126,8 +129,11 @@ module.exports = (app) => {
|
||||
router.delete('/api/web/workstations/:id/scan-channels/:linkId', apiAuth, subjectAuth, controller.web.workstation.unbindScanChannel);
|
||||
|
||||
// 前端「测试页」的模拟接口(模拟设备扫码登录 / 模拟中控上报),与真机走同一套 service
|
||||
router.post('/api/web/test/device-login', apiAuth, subjectAuth, controller.web.test.deviceLogin);
|
||||
router.post('/api/web/test/scan', apiAuth, subjectAuth, controller.web.test.scan);
|
||||
// 只在非生产环境注册:生产不暴露模拟链路
|
||||
if (app.config.env !== 'prod') {
|
||||
router.post('/api/web/test/device-login', apiAuth, subjectAuth, controller.web.test.deviceLogin);
|
||||
router.post('/api/web/test/scan', apiAuth, subjectAuth, controller.web.test.scan);
|
||||
}
|
||||
|
||||
// ---------- 运维/内部(脚本、后台系统;**需内部令牌**,见 middleware/internal_auth.js)----------
|
||||
router.get('/api/users', internalAuth, controller.internal.user.index);
|
||||
|
||||
@ -26,7 +26,8 @@ class MailService extends Service {
|
||||
const text = `你的 ${site} 注册验证码是 ${code},${minutes} 分钟内有效。\n`
|
||||
+ '如果不是你本人操作,忽略本邮件即可。';
|
||||
|
||||
if (cfg.devMode) {
|
||||
const devMode = this.app.config.env !== 'prod' && cfg.devMode;
|
||||
if (devMode) {
|
||||
this.ctx.logger.info('[mail][dev] 未配置 SMTP,验证码不发真邮件 → %s : %s', email, code);
|
||||
return { devMode: true, code };
|
||||
}
|
||||
@ -50,7 +51,8 @@ class MailService extends Service {
|
||||
+ `${url}\n`
|
||||
+ '如果不是你本人操作,忽略本邮件即可,你的密码不会被修改。';
|
||||
|
||||
if (cfg.devMode) {
|
||||
const devMode = this.app.config.env !== 'prod' && cfg.devMode;
|
||||
if (devMode) {
|
||||
this.ctx.logger.info('[mail][dev] 未配置 SMTP,重置链接不发真邮件 → %s : %s', email, url);
|
||||
return { devMode: true, url };
|
||||
}
|
||||
|
||||
@ -95,7 +95,9 @@ class PasswordResetService extends Service {
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[reset] 重置链接已生成 user=%s email=%s', user.id, user.email);
|
||||
return { ok: true, devMode: mail.devMode, url: mail.devMode ? url : undefined };
|
||||
// 生产环境绝不回传重置链接(即使配置误开 devMode 也兜底)
|
||||
const exposeDevUrl = this.app.config.env !== 'prod' && !!mail.devMode;
|
||||
return { ok: true, devMode: exposeDevUrl, url: exposeDevUrl ? url : undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -62,13 +62,15 @@ class VerifyCodeService extends Service {
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[verify] %s 验证码已生成: %s (devMode=%s)', scene, email, !!mail.devMode);
|
||||
// 生产环境绝不回传验证码(即使配置误开 devMode 也兜底)
|
||||
const exposeDevCode = this.app.config.env !== 'prod' && !!mail.devMode;
|
||||
return {
|
||||
ok: true,
|
||||
ttl: this.cfg.codeTtl,
|
||||
resendInterval: this.cfg.resendInterval,
|
||||
devMode: !!mail.devMode,
|
||||
devMode: exposeDevCode,
|
||||
// 开发模式才把验证码回传给页面(生产走邮件)
|
||||
code: mail.devMode ? code : undefined,
|
||||
code: exposeDevCode ? code : undefined,
|
||||
};
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[verify] 验证码发送失败 %s : %s', email, err.message);
|
||||
|
||||
@ -14,6 +14,10 @@ module.exports = (appInfo) => {
|
||||
// cookie/session 签名用的 key,生产环境请改成随机字符串
|
||||
config.keys = `${appInfo.name}_1729000000000_1971`;
|
||||
|
||||
// 部署在 nginx 后面:信任 X-Forwarded-Proto / X-Forwarded-For,
|
||||
// 否则 ctx.origin / ctx.protocol 会一直认为是 http,二维码、邮件链接会拼成 http://
|
||||
config.proxy = true;
|
||||
|
||||
// ==================== 站点/产品名 ====================
|
||||
// 页标题、品牌位、邮件正文都用它 —— **改名字只改这里**(或设环境变量 SITE_NAME)
|
||||
config.siteName = env.SITE_NAME || '云仓视频溯源系统';
|
||||
@ -35,17 +39,21 @@ module.exports = (appInfo) => {
|
||||
};
|
||||
|
||||
// ==================== 安装包分发(软件自动更新) ====================
|
||||
// 打包脚本(desktop/installer/build.ps1)会把:
|
||||
// - MSI → app/public/download/ (egg-static 提供 /download/xxx.msi,文件名带版本号→可长缓存)
|
||||
// - version.json → app/public/version/ (**不在静态目录里**,由 controller/download.js 提供,
|
||||
// 因为 koa-static 命中后不 next(),改不了它的缓存头)
|
||||
// 软件启动时请求 GET /download/version.json 判断是否有新版本。
|
||||
// 打包脚本会把产物放进按平台划分的子目录:
|
||||
// - 桌面端 desktop/installer/build.ps1
|
||||
// MSI → app/public/download/desktop/ (egg-static 提供 /download/desktop/*.msi,长缓存)
|
||||
// version.json → app/public/version/desktop/ (**不在静态目录里**,由 controller/download.js 提供,
|
||||
// 因为 koa-static 命中后不 next(),改不了缓存头)
|
||||
// - Android backend/android_client/build.ps1
|
||||
// APK → app/public/download/android_client/ (/download/android_client/*.apk)
|
||||
// version.json → app/public/version/android_client/
|
||||
// 桌面端软件启动时请求 GET /download/version.json 判断是否有新版本(路径不能改,老客户端写死了)。
|
||||
config.static = {
|
||||
prefix: '/download/',
|
||||
dir: path.join(appInfo.baseDir, 'app/public/download'),
|
||||
// 这里只会放“文件名带版本号”的 MSI,内容永不变 → 可以放心长缓存
|
||||
// 这里只会放“文件名带版本号”的 MSI / APK,内容永不变 → 可以放心长缓存
|
||||
maxAge: 31536000,
|
||||
buffer: false, // MSI 几十 MB,流式发送
|
||||
buffer: false, // MSI / APK 几十 MB,流式发送
|
||||
};
|
||||
|
||||
// ==================== 前端入口(页面不在后端渲染) ====================
|
||||
@ -208,7 +216,8 @@ module.exports = (appInfo) => {
|
||||
// ==================== 邮件 / 邮箱验证码(注册时需要验证邮箱) ====================
|
||||
config.email = {
|
||||
// 未配置 SMTP_HOST 时走开发模式:验证码写日志并在注册页回显(仅本地/测试用)
|
||||
devMode: !env.SMTP_HOST,
|
||||
// ⚠️ 生产环境(env=prod)永远不启用 devMode,避免把验证码 / 重置链接回传给前端
|
||||
devMode: appInfo.env !== 'prod' && !env.SMTP_HOST,
|
||||
// 发件人显示名用站点名(邮箱域名保持 pack-service.local,技术标识不动)
|
||||
from: env.SMTP_FROM || `${config.siteName} <no-reply@pack-service.local>`,
|
||||
smtp: {
|
||||
|
||||
99
backend/config/deploy.config.example.cjs
Normal file
99
backend/config/deploy.config.example.cjs
Normal file
@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发布配置模板(提交到仓库)
|
||||
*
|
||||
* 复制为 config/deploy.config.local.cjs 后填入真实 SSH 信息:
|
||||
* Copy-Item config/deploy.config.example.cjs config/deploy.config.local.cjs
|
||||
*
|
||||
* config/deploy.config.local.cjs 已被 .gitignore 忽略,禁止提交。
|
||||
*/
|
||||
module.exports = {
|
||||
production: {
|
||||
// ==================== SSH ====================
|
||||
host: '__FILL_SSH_HOST__',
|
||||
port: 22,
|
||||
username: '__FILL_SSH_USERNAME__',
|
||||
// 绝对路径;Windows 写法示例:C:/Users/you/.ssh/id_rsa
|
||||
privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa',
|
||||
|
||||
// ==================== 远端目录 ====================
|
||||
// 双实例目录:${deployRoot}/v1、${deployRoot}/v2;
|
||||
// ${deployRoot}/current.md 记录当前活跃版本,${deployRoot}/.deploy 存放发布包/备份/状态。
|
||||
deployRoot: '/www/wwwroot/packService',
|
||||
|
||||
// v1 / v2 两个实例的监听端口(egg config.cluster.listen.port 由启动脚本的 PORT 覆盖)
|
||||
ports: { v1: 7301, v2: 7302 },
|
||||
|
||||
// ==================== 健康检查 ====================
|
||||
// /health 会同时检查 MySQL / Redis,任一不可用即 503
|
||||
healthCheckPath: '/health',
|
||||
healthCheckAttempts: 30,
|
||||
healthCheckInterval: 2,
|
||||
|
||||
// Nginx upstream 文件(内容只有一行 proxy_pass)。置空字符串则不自动切换。
|
||||
// 需要在 Nginx 配置里 include 这个文件,例如:
|
||||
// upstream pack_service { include /www/wwwroot/packService/nginx-upstream.conf; }
|
||||
nginxUpstreamFile: '/www/wwwroot/packService/nginx-upstream.conf',
|
||||
|
||||
// 服务端私有配置目录(不随发布包走):可放 config.prod.js / config.local.js;
|
||||
// envFile 会在启动前被 source,用于 JWT_SECRET、数据库密码等环境变量。
|
||||
sharedConfigDir: '/www/wwwroot/packService/shared-config',
|
||||
envFile: 'env.prod.sh',
|
||||
// 本机权威 env 副本(已 gitignore);存在时发布前自动上传到 shared-config/
|
||||
envFileLocalPath: 'config/env.prod.sh',
|
||||
uploadEnvFile: true,
|
||||
|
||||
// ==================== 发布内容 ====================
|
||||
// 远端保留目录(清理旧代码时跳过)
|
||||
sharedDirs: [ 'node_modules', 'logs', 'run', 'temp' ],
|
||||
|
||||
// 服务端私有文件/目录:发布前暂存、解压后放回,不会被发布包覆盖或删除。
|
||||
// config/config.prod.js 需要运维在服务器上首次放置(数据库/Redis 密码等)。
|
||||
preservePaths: [
|
||||
'config/config.prod.js',
|
||||
'config/config.local.js',
|
||||
'app/public/download',
|
||||
'app/public/version',
|
||||
],
|
||||
|
||||
// 发布前本地构建 ../frontend,产物单独上传到 frontendDeployDir(由 nginx 托管)
|
||||
buildFrontend: true,
|
||||
frontendDir: '../frontend',
|
||||
// 前端构建产物由 nginx 直接托管(上一版保留在 frontend.prev,供回退)
|
||||
frontendDeployDir: '/www/wwwroot/packService/frontend',
|
||||
// 由发布脚本维护的 nginx 前端/反代配置(站点配置里 include)
|
||||
nginxFrontConf: '/www/wwwroot/packService/front.conf',
|
||||
manageNginxFrontConf: true,
|
||||
serverName: 'pack.example.com',
|
||||
// 桌面端发布(npm run desktop:publish):只构建/上传安装包,不动后端
|
||||
desktopBuildScript: '../desktop/installer/build.ps1',
|
||||
desktopOutDir: '../desktop/installer/out',
|
||||
// 安装包目录(nginx 长缓存):deployRoot/download/desktop/YuncangTraceSetup-x.y.z.msi
|
||||
desktopDownloadDir: '/www/wwwroot/packService/download/desktop',
|
||||
// version.json 目录(nginx 对 /download/version.json 关缓存,客户端路径不变)
|
||||
desktopVersionDir: '/www/wwwroot/packService/download',
|
||||
desktopBaseUrl: 'https://pack.example.com',
|
||||
desktopKeepVersions: 5,
|
||||
desktopOwner: 'www:www',
|
||||
|
||||
// Android 设备端发布(npm run android:publish):同样只构建/上传 APK
|
||||
androidBuildScript: 'android_client/build.ps1',
|
||||
androidOutDir: 'android_client/out',
|
||||
androidDownloadDir: '/www/wwwroot/packService/download/android_client',
|
||||
androidVersionDir: '/www/wwwroot/packService/download/android_client',
|
||||
androidBaseUrl: 'https://pack.example.com',
|
||||
androidKeepVersions: 5,
|
||||
androidOwner: 'www:www',
|
||||
|
||||
// 目标目录 npm install --production 后是否执行 npm run db:deploy
|
||||
remoteDbDeploy: false,
|
||||
|
||||
// 保留最近多少个备份包(backup-*.tar.gz)
|
||||
keepBackups: 5,
|
||||
|
||||
sshOptions: [
|
||||
'StrictHostKeyChecking=accept-new',
|
||||
],
|
||||
},
|
||||
};
|
||||
@ -3,7 +3,7 @@
|
||||
/**
|
||||
* sequelize-cli 配置入口(`.sequelizerc` 指到这里)
|
||||
*
|
||||
* 连接信息与后端运行时**完全同源**:环境变量 > config/config.local.js > 默认值,
|
||||
* 连接信息与后端运行时**完全同源**:环境变量 > config/config.prod.js(EGG_SERVER_ENV=prod)> config/config.local.js > 默认值,
|
||||
* 统一由 scripts/db-config.js 解析,避免迁移改到一个库、服务连另一个库。
|
||||
*
|
||||
* 用法:
|
||||
|
||||
@ -9,10 +9,37 @@
|
||||
*
|
||||
* 数据迁移:给**已有数据**的用户各建一个主体(管理员=本人,期限 +365 天),
|
||||
* 并把其名下数据回填到该主体,保证升级后旧数据仍然可见。
|
||||
*
|
||||
* 注意:`sql/schema.sql` 基线可能已经包含 `scan_records.subject_id` 等列,
|
||||
* 所以这里所有建表 / 加列 / 加索引都做成幂等,空库和旧库都能反复执行。
|
||||
*/
|
||||
|
||||
async function hasTable(queryInterface, table) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(item => (typeof item === 'string' ? item : Object.values(item)[0]) === table);
|
||||
}
|
||||
|
||||
async function hasColumn(queryInterface, table, column) {
|
||||
try {
|
||||
const description = await queryInterface.describeTable(table);
|
||||
return Boolean(description[column]);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function hasIndex(queryInterface, table, name) {
|
||||
try {
|
||||
const indexes = await queryInterface.showIndex(table);
|
||||
return indexes.some(item => item.name === name);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, TINYINT, DATE, INTEGER } = Sequelize;
|
||||
const { BIGINT, STRING, TINYINT, DATE } = Sequelize;
|
||||
|
||||
const audit = {
|
||||
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
@ -20,37 +47,49 @@ module.exports = {
|
||||
deleted_at: { type: DATE, allowNull: true },
|
||||
};
|
||||
|
||||
await queryInterface.createTable('subjects', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
name: { type: STRING(64), allowNull: false, comment: '主体名称' },
|
||||
admin_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员用户 users.id(默认创建人)' },
|
||||
expire_at: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
|
||||
remark: { type: STRING(255), allowNull: true, comment: '备注' },
|
||||
...audit,
|
||||
}, { comment: '主体表' });
|
||||
if (!await hasTable(queryInterface, 'subjects')) {
|
||||
await queryInterface.createTable('subjects', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
name: { type: STRING(64), allowNull: false, comment: '主体名称' },
|
||||
admin_user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '管理员用户 users.id(默认创建人)' },
|
||||
expire_at: { type: DATE, allowNull: false, comment: '使用期限(到期后不可进入)' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
|
||||
remark: { type: STRING(255), allowNull: true, comment: '备注' },
|
||||
...audit,
|
||||
}, { comment: '主体表' });
|
||||
}
|
||||
|
||||
await queryInterface.addIndex('subjects', [ 'admin_user_id' ], { name: 'idx_subjects_admin' });
|
||||
await queryInterface.addIndex('subjects', [ 'expire_at' ], { name: 'idx_subjects_expire' });
|
||||
if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_admin')) {
|
||||
await queryInterface.addIndex('subjects', [ 'admin_user_id' ], { name: 'idx_subjects_admin' });
|
||||
}
|
||||
if (!await hasIndex(queryInterface, 'subjects', 'idx_subjects_expire')) {
|
||||
await queryInterface.addIndex('subjects', [ 'expire_at' ], { name: 'idx_subjects_expire' });
|
||||
}
|
||||
|
||||
await queryInterface.createTable('subject_members', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
|
||||
user_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定账号 users.id(未绑定为空)' },
|
||||
name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
|
||||
role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
|
||||
wechat_openid: { type: STRING(64), allowNull: true, comment: '绑定的微信 openid' },
|
||||
bound_at: { type: DATE, allowNull: true, comment: '成员绑定账号/微信的时间' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
|
||||
...audit,
|
||||
}, { comment: '主体成员表' });
|
||||
if (!await hasTable(queryInterface, 'subject_members')) {
|
||||
await queryInterface.createTable('subject_members', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
|
||||
user_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定账号 users.id(未绑定为空)' },
|
||||
name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
|
||||
role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
|
||||
wechat_openid: { type: STRING(64), allowNull: true, comment: '绑定的微信 openid' },
|
||||
bound_at: { type: DATE, allowNull: true, comment: '成员绑定账号/微信的时间' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
|
||||
...audit,
|
||||
}, { comment: '主体成员表' });
|
||||
}
|
||||
|
||||
// 同一主体下同一账号只能有一条(NULL 不参与唯一性,所以「未绑定的成员」可以有多条)
|
||||
await queryInterface.addIndex('subject_members', [ 'subject_id', 'user_id' ], {
|
||||
name: 'uk_subject_members_subject_user',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex('subject_members', [ 'user_id' ], { name: 'idx_subject_members_user' });
|
||||
if (!await hasIndex(queryInterface, 'subject_members', 'uk_subject_members_subject_user')) {
|
||||
await queryInterface.addIndex('subject_members', [ 'subject_id', 'user_id' ], {
|
||||
name: 'uk_subject_members_subject_user',
|
||||
unique: true,
|
||||
});
|
||||
}
|
||||
if (!await hasIndex(queryInterface, 'subject_members', 'idx_subject_members_user')) {
|
||||
await queryInterface.addIndex('subject_members', [ 'user_id' ], { name: 'idx_subject_members_user' });
|
||||
}
|
||||
|
||||
// 业务表挂到主体
|
||||
const targets = [
|
||||
@ -62,25 +101,34 @@ module.exports = {
|
||||
[ 'scan_records', '扫码记录表' ],
|
||||
];
|
||||
for (const [ table ] of targets) {
|
||||
await queryInterface.addColumn(table, 'subject_id', {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '所属主体 subjects.id',
|
||||
after: 'id',
|
||||
});
|
||||
await queryInterface.addIndex(table, [ 'subject_id' ], { name: `idx_${table}_subject` });
|
||||
if (!await hasColumn(queryInterface, table, 'subject_id')) {
|
||||
await queryInterface.addColumn(table, 'subject_id', {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '所属主体 subjects.id',
|
||||
after: 'id',
|
||||
});
|
||||
}
|
||||
if (!await hasIndex(queryInterface, table, `idx_${table}_subject`)) {
|
||||
await queryInterface.addIndex(table, [ 'subject_id' ], { name: `idx_${table}_subject` });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 回填:给已有数据的用户建主体 ----------------
|
||||
const expireExpr = "DATE_ADD(NOW(), INTERVAL 365 DAY)";
|
||||
const expireExpr = 'DATE_ADD(NOW(), INTERVAL 365 DAY)';
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO subjects (name, admin_user_id, expire_at, status, remark, created_at, updated_at)
|
||||
SELECT LEFT(CONCAT(COALESCE(NULLIF(u.nickname, ''), NULLIF(u.username, ''), CONCAT('用户', u.id)), ' 的主体'), 64),
|
||||
u.id, ${expireExpr}, 1, '升级时自动创建的历史主体', NOW(), NOW()
|
||||
FROM users u
|
||||
WHERE EXISTS (SELECT 1 FROM nvrs n WHERE n.user_id = u.id AND n.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM workstations w WHERE w.user_id = u.id AND w.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM scanners s WHERE s.user_id = u.id AND s.deleted_at IS NULL)
|
||||
WHERE (
|
||||
EXISTS (SELECT 1 FROM nvrs n WHERE n.user_id = u.id AND n.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM workstations w WHERE w.user_id = u.id AND w.deleted_at IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM scanners s WHERE s.user_id = u.id AND s.deleted_at IS NULL)
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM subjects s2 WHERE s2.admin_user_id = u.id AND s2.deleted_at IS NULL
|
||||
)
|
||||
`);
|
||||
|
||||
await queryInterface.sequelize.query(`
|
||||
|
||||
@ -13,36 +13,66 @@
|
||||
* 索引:
|
||||
* - `(subject_id, barcode)`:按运单号查(主体内精确匹配)
|
||||
* - `(scanner_id, channel_id, scan_time)`:散单要取同通道的「上一条/下一条」扫码时间
|
||||
*
|
||||
* 注意:`sql/schema.sql` 基线已经包含这些列和索引,空库执行时必须幂等。
|
||||
*/
|
||||
|
||||
async function hasColumn(queryInterface, table, column) {
|
||||
try {
|
||||
const description = await queryInterface.describeTable(table);
|
||||
return Boolean(description[column]);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function hasIndex(queryInterface, table, name) {
|
||||
try {
|
||||
const indexes = await queryInterface.showIndex(table);
|
||||
return indexes.some(item => item.name === name);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, JSON: JSONType } = Sequelize;
|
||||
|
||||
await queryInterface.addColumn('scan_records', 'workstation_id', {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '当时绑定的工作台 workstations.id(快照里有完整信息)',
|
||||
});
|
||||
if (!await hasColumn(queryInterface, 'scan_records', 'workstation_id')) {
|
||||
await queryInterface.addColumn('scan_records', 'workstation_id', {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '当时绑定的工作台 workstations.id(快照里有完整信息)',
|
||||
});
|
||||
}
|
||||
|
||||
await queryInterface.addColumn('scan_records', 'workstation_snapshot', {
|
||||
type: JSONType,
|
||||
allowNull: true,
|
||||
comment: '工作台快照(录像机/摄像头/布局/录制范围),回放按它拉流',
|
||||
});
|
||||
if (!await hasColumn(queryInterface, 'scan_records', 'workstation_snapshot')) {
|
||||
await queryInterface.addColumn('scan_records', 'workstation_snapshot', {
|
||||
type: JSONType,
|
||||
allowNull: true,
|
||||
comment: '工作台快照(录像机/摄像头/布局/录制范围),回放按它拉流',
|
||||
});
|
||||
}
|
||||
|
||||
await queryInterface.addIndex('scan_records', [ 'subject_id', 'barcode' ], {
|
||||
name: 'idx_scan_subject_barcode',
|
||||
});
|
||||
if (!await hasIndex(queryInterface, 'scan_records', 'idx_scan_subject_barcode')) {
|
||||
await queryInterface.addIndex('scan_records', [ 'subject_id', 'barcode' ], {
|
||||
name: 'idx_scan_subject_barcode',
|
||||
});
|
||||
}
|
||||
|
||||
await queryInterface.addIndex('scan_records', [ 'scanner_id', 'channel_id', 'scan_time' ], {
|
||||
name: 'idx_scan_channel_seq',
|
||||
});
|
||||
if (!await hasIndex(queryInterface, 'scan_records', 'idx_scan_channel_seq')) {
|
||||
await queryInterface.addIndex('scan_records', [ 'scanner_id', 'channel_id', 'scan_time' ], {
|
||||
name: 'idx_scan_channel_seq',
|
||||
});
|
||||
}
|
||||
|
||||
// 中控上报时按 (scanner_id, channel_id) 找工作台,没索引会全表扫
|
||||
await queryInterface.addIndex('workstation_scan_channels', [ 'scanner_id', 'channel_id' ], {
|
||||
name: 'idx_wsc_scanner_channel',
|
||||
});
|
||||
if (!await hasIndex(queryInterface, 'workstation_scan_channels', 'idx_wsc_scanner_channel')) {
|
||||
await queryInterface.addIndex('workstation_scan_channels', [ 'scanner_id', 'channel_id' ], {
|
||||
name: 'idx_wsc_scanner_channel',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
|
||||
@ -14,29 +14,48 @@
|
||||
* - 每组保留:`scan_time` 最新的那一条,时间相同时保留 `id` 最大的(最后写入);
|
||||
* - 其余行**物理删除**(scan_records 是流水表,没有软删除)。
|
||||
*
|
||||
* 兼容性:生产 MySQL 5.7 不支持窗口函数(ROW_NUMBER),这里用
|
||||
* 「先按组查重、再逐组取最新一条」的方式实现,空表直接跳过。
|
||||
*
|
||||
* 不可逆:down() 不做恢复(被删的都是同一运单的旧记录,没有保留价值)。
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(`
|
||||
SELECT id FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY COALESCE(subject_id, 0), barcode
|
||||
ORDER BY scan_time DESC, id DESC
|
||||
) AS rn
|
||||
FROM scan_records
|
||||
) ranked
|
||||
WHERE rn > 1
|
||||
const [ groups ] = await queryInterface.sequelize.query(`
|
||||
SELECT COALESCE(subject_id, 0) AS sid, barcode, COUNT(*) AS total
|
||||
FROM scan_records
|
||||
GROUP BY COALESCE(subject_id, 0), barcode
|
||||
HAVING COUNT(*) > 1
|
||||
`);
|
||||
|
||||
const ids = rows.map(row => Number(row.id));
|
||||
if (!ids.length) {
|
||||
if (!groups.length) {
|
||||
console.log('[dedupe] scan_records 没有重复运单号,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
const ids = [];
|
||||
for (const group of groups) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
`SELECT id
|
||||
FROM scan_records
|
||||
WHERE COALESCE(subject_id, 0) = ?
|
||||
AND barcode = ?
|
||||
ORDER BY scan_time DESC, id DESC`,
|
||||
{ replacements: [ group.sid, group.barcode ] }
|
||||
);
|
||||
|
||||
// 第一条是「最新一条」,其余都是重复记录
|
||||
for (const row of rows.slice(1)) {
|
||||
ids.push(Number(row.id));
|
||||
}
|
||||
}
|
||||
|
||||
if (!ids.length) {
|
||||
console.log('[dedupe] scan_records 没有需要删除的重复记录');
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.bulkDelete('scan_records', { id: ids });
|
||||
console.log(`[dedupe] 已删除 ${ids.length} 条重复扫码记录(同一运单号只保留最后一条)`);
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user