diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..07936db --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh +# 禁止提交服务端私有配置 / 运行期产物 / 版本记录(参考 wms 的 .githooks/pre-commit) +node backend/scripts/deploy/git-safety-check.cjs diff --git a/.gitignore b/.gitignore index 332a55e..8f32af1 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/AndroidStation/.github/copilot-instructions.md b/AndroidStation/.github/copilot-instructions.md new file mode 100644 index 0000000..e3c3a6f --- /dev/null +++ b/AndroidStation/.github/copilot-instructions.md @@ -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` 逻辑复制进来。 diff --git a/AndroidStation/.gitignore b/AndroidStation/.gitignore new file mode 100644 index 0000000..fcb9bb0 --- /dev/null +++ b/AndroidStation/.gitignore @@ -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/ diff --git a/AndroidStation/.vscode/tasks.json b/AndroidStation/.vscode/tasks.json new file mode 100644 index 0000000..94b391c --- /dev/null +++ b/AndroidStation/.vscode/tasks.json @@ -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": [] + } + ] +} \ No newline at end of file diff --git a/AndroidStation/AndroidStation.code-workspace b/AndroidStation/AndroidStation.code-workspace new file mode 100644 index 0000000..876a149 --- /dev/null +++ b/AndroidStation/AndroidStation.code-workspace @@ -0,0 +1,8 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": {} +} \ No newline at end of file diff --git a/AndroidStation/README.md b/AndroidStation/README.md new file mode 100644 index 0000000..9081aae --- /dev/null +++ b/AndroidStation/README.md @@ -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 上报)。 + 本工程只负责「当一台扫码设备」。 diff --git a/AndroidStation/app/build.gradle b/AndroidStation/app/build.gradle new file mode 100644 index 0000000..7a1ccae --- /dev/null +++ b/AndroidStation/app/build.gradle @@ -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' +} diff --git a/AndroidStation/app/proguard-rules.pro b/AndroidStation/app/proguard-rules.pro new file mode 100644 index 0000000..fe468dc --- /dev/null +++ b/AndroidStation/app/proguard-rules.pro @@ -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(...); +} diff --git a/AndroidStation/app/src/main/AndroidManifest.xml b/AndroidStation/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..98e1065 --- /dev/null +++ b/AndroidStation/app/src/main/AndroidManifest.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java new file mode 100644 index 0000000..1dbd436 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/App.java @@ -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; + +/** + * 持有进程级单例。 + * + *

发现应答和扫码服务属于整个进程,不挂在页面上:页面重建、切换前后台都不能让 + * 桌面端的连接断开,也不能让设备从局域网里消失。 + */ +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; + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java new file mode 100644 index 0000000..09adefb --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/MainActivity.java @@ -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; + +/** + * 设备端主界面:显示本机身份、服务状态和最近扫码结果。 + * + *

USB 扫码枪是键盘设备,这里在 Activity 层统一收键(不依赖某个输入框有没有焦点): + * 连续可打印字符攒成一条条码,回车/Tab 立即提交;没有后缀时停手 + * {@link #FLUSH_DELAY_MS} 后自动提交,兼容不带后缀的扫码枪。 + * + *

扫码热路径不碰 UI:按键只追加到缓冲并立即提交,不同步刷新任何 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 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 位。 + * + *

热路径上不用正则:手工扫首尾比 {@code replaceAll} 少两次 Pattern 匹配和字符串分配。 + * 注意不做任何去重——重复条码也必须原样上报。 + */ + 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(); + } + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java new file mode 100644 index 0000000..eb9dd28 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/SettingsActivity.java @@ -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; + +/** + * 服务设置:只配置设备名、扫码服务端口、发现端口和启停开关。 + * + *

按现场要求不提供改 IP 的入口:设备地址由网络分配,应用只负责应答发现和推扫码数据。 + */ +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)); + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java new file mode 100644 index 0000000..d811b87 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationIdentity.java @@ -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; + +/** + * 本机在「设备」身份下的固定信息。 + * + *

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 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; + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java new file mode 100644 index 0000000..f86425a --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/StationSettings.java @@ -0,0 +1,95 @@ +package com.gztbyc.scancenter.core; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Build; + +/** + * 设备端服务参数。 + * + *

本机扮演「网口扫码设备」:对局域网广播应答发现报文,并在服务端口上监听, + * 把 USB 扫码枪的结果推给连上来的桌面端。这里只存服务参数,不再保存任何 IP/掩码/网关 + * —— 设备地址由现场网络分配,改地址不属于本应用职责。 + */ +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(); + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java new file mode 100644 index 0000000..83a63a4 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/DiscoveryResponder.java @@ -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 端口上响应桌面端的发现广播。 + * + *

桌面端({@code Services/Scan/DiscoveryMonitor.cs})每 3 秒往 + * {@code 255.255.255.255:48899} 发一段 {@code {"Type":"EP_Tool",...}}, + * 设备把**自己的信息**回给发送方的源地址/源端口。这里必须用同一个 socket + * 收和回,否则源端口对不上,桌面端收不到。 + * + *

同时兼容桌面端的 JCMD 配置报文({@code CID 10001/10003/10005/10017}): + * 桌面端「添加通道」时会读 SOCK 段确认 TCP 服务、把设备名写进 SYS 段。 + * 网络参数只读不写:本机不改 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; + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java new file mode 100644 index 0000000..2f7b7b9 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/ScanServer.java @@ -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 扫码枪的结果。 + * + *

方向与现场网口设备一致(见桌面端 {@code ChannelConnection.cs}): + * 设备监听、桌面端主动连接。每收到一条扫码结果,按行(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 clients = new CopyOnWriteArrayList(); + + /** + * 扫码结果是在主线程(按键回调)产生的,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(); + } + + /** + * 把一条扫码结果推给所有客户端。 + * + *

⚠️ 不去重:重复条码也照发,连续扫描的重复帧由桌面端自己判断。 + * 这里只做两件事——复制成字节、丢给后台写线程,调用方(按键回调)立即返回。 + */ + 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) { + // 忽略 + } + } + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java new file mode 100644 index 0000000..342cd35 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/service/StationService.java @@ -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; + +/** + * 设备端服务总入口:发现应答 + 扫码推送。 + * + *

进程级单例,随 {@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 listeners = new CopyOnWriteArrayList(); + private final ArrayDeque history = new ArrayDeque(); + + 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); + } + + /** + * 收到一条扫码结果:记入历史并推给所有桌面端连接。 + * + *

无论服务是否启用都记账 —— 现场排查时「扫了但没推出去」比「没扫上」更难分辨。 + */ + 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 history() { + synchronized (history) { + return new ArrayList(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(); + } + } + }); + } + +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java new file mode 100644 index 0000000..486ac64 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/core/speech/BarcodeSpeaker.java @@ -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; + +/** + * 离线语音播报:播「条码后四位 + 开始打包」。 + * + *

设备上只有 PicoTts 且没有中文语音数据,所以运行时不用 TextToSpeech: + * 事先用 `tools/fetch-voice-seeds.ps1` 从现场语音服务把 0-9、A-Z、「开始打包」 + * 一次性抓成 44.1kHz/立体声/16-bit PCM,放在 {@code res/raw}。运行时只读本地资源, + * 断网也能播报。 + * + *

播放用系统 {@link MediaPlayer} 读一个临时拼接的 WAV:这台 rk3288 的 + * AudioTrack 直接初始化会失败,MediaPlayer 由音频框架负责重采样/路由,兼容性更好。 + * + *

播报与扫码上报互不阻塞:拼 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 pcmCache = new HashMap(); + + 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); + } + + /** + * 收到一条扫码结果后调用。 + * + *

只做很轻的判重和入队;拼 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; + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java new file mode 100644 index 0000000..9796bc6 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/receiver/BootReceiver.java @@ -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; + +/** + * 开机自启动:工位设备断电重启后自动进入设备端主界面。 + * + *

应用本体是服务型终端,主界面只是状态展示,所以直接拉起 {@link MainActivity}。 + * + *

为什么可以直接 startActivity: + *

+ * + *

⚠️ 应用新装且从未启动过时处于 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); + } + } +} diff --git a/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java new file mode 100644 index 0000000..9898f20 --- /dev/null +++ b/AndroidStation/app/src/main/java/com/gztbyc/scancenter/util/L.java @@ -0,0 +1,168 @@ +package com.gztbyc.scancenter.util; + +import android.util.Log; + +import com.gztbyc.scancenter.BuildConfig; + +import java.util.Arrays; + +/** + * 轻量日志工具:静态导入之后就能像 console.log 一样一次打印多个参数。 + * + *

+ * import static com.gztbyc.scancenter.util.L.*;
+ *
+ * log("扫码结果", code, "耗时", ms);
+ * e(exception, "请求失败", url);
+ * 
+ * + *

设计要点: + *

+ */ +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(); + } + + /** + * 取调用方位置(类名.方法名:行号)。 + * + *

做法是「跳过 L 自己的所有连续栈帧,取紧随其后的那一帧」,而不是 + * 「跳过 class == L 的帧」—— 后者在 Android 上会出错: + * {@code Thread.getStackTrace()} 的栈顶是 {@code dalvik.system.VMStack.getThreadStackTrace} + * (行号 -2,native 方法),它既不是 L 也不是 Thread,会被当成调用方返回, + * 于是每条日志的前缀都变成 {@code VMStack.getThreadStackTrace:-2}。 + * + *

顺带也处理了 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)); + } + } +} diff --git a/AndroidStation/app/src/main/res/drawable/app_banner.xml b/AndroidStation/app/src/main/res/drawable/app_banner.xml new file mode 100644 index 0000000..aea2109 --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/app_banner.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/bg_button.xml b/AndroidStation/app/src/main/res/drawable/bg_button.xml new file mode 100644 index 0000000..930c3b9 --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/bg_button.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml b/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml new file mode 100644 index 0000000..01e8d3a --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/bg_button_danger.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/bg_card.xml b/AndroidStation/app/src/main/res/drawable/bg_card.xml new file mode 100644 index 0000000..174eacb --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/bg_card.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/bg_header.xml b/AndroidStation/app/src/main/res/drawable/bg_header.xml new file mode 100644 index 0000000..742f1be --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/bg_header.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/bg_panel.xml b/AndroidStation/app/src/main/res/drawable/bg_panel.xml new file mode 100644 index 0000000..326e5ec --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/bg_panel.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml b/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..45b7e64 --- /dev/null +++ b/AndroidStation/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + diff --git a/AndroidStation/app/src/main/res/layout/activity_main.xml b/AndroidStation/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..a6ab6de --- /dev/null +++ b/AndroidStation/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,373 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +